char指针与c ++中的cout混淆 [英] char pointer confusing with cout in c++
问题描述
当我用 printf()
打印一个字符指针时,它使用转换说明符来决定是打印地址还是根据%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
做同样的事情时, / code>决定什么应该打印在地址和整个字符串?这里是一个示例源:
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.
我如何获得 ch
的地址 cptr
使用 cout
?
How I can get address of ch
via cptr
using cout
?
推荐答案
过载解析选择 ostream&用于打印C风格字符串的操作符<<(ostream& o,const char * c);
你想要另一个 ostream&运算符<<(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指针与c ++中的cout混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!