Why does streaming a char pointer to cout not print an address?(为什么将 char 指针流式传输到 cout 不打印地址?)
问题描述
当我用 printf() 打印一个 char 指针时,它会根据 %u 或 %s 使用转换说明符来决定是打印地址还是打印整个字符串.
When I print a char pointer with printf(), it makes the decision with conversion specifier whether the address should be printed or the whole string according to %u or %s.
但是当我想用 cout 做同样的事情时,cout 将如何决定应该在地址和整个字符串之间打印什么?这是一个示例来源:
But when I want to do the same thing with cout, how will cout decide what should be printed among address and whole string? Here is an example source:
int main()
{
char ch='a';
char *cptr=&ch;
cout<<cptr<<endl;
return 0;
}
这里,在我的 GNU 编译器中,cout 试图将 ch 输出为字符串.
Here, in my GNU compiler, cout is trying to output ch as a string.
如何使用 cout 通过 cptr 获取 ch 的地址?
How I can get address of ch via cptr using cout?
推荐答案
重载分辨率选择ostream&operator<<(ostream& o, const char *c); 用于打印 C 风格的字符串.你想要另一个 ostream&operator<<(ostream&o, const void *p); 被选中.您可能最好在此处使用演员表:
Overload resolution selects the ostream& operator<<(ostream& o, const char *c); which is used for printing C-style strings. You want the other ostream& operator<<(ostream& o, const void *p); to be selected. You are probably best off with a cast here:
cout << static_cast<void *>(cptr) << endl;
这篇关于为什么将 char 指针流式传输到 cout 不打印地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么将 char 指针流式传输到 cout 不打印地址?
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
