字符指针与cout中的cout混淆

当我用printf()打印一个字符指针时,它会根据转换说明符决定是打印地址还是根据%u或%s打印整个string。

但是当我想用cout做同样的事情时, cout怎么决定在地址和整个string之间应该打印什么呢? 这里是一个例子来源:

 int main() { char ch='a'; char *cptr=&ch; cout<<cptr<<endl; return 0; } 

在这里,在我的GNU编译器中, cout正在尝试将ch输出为string。

如何通过cout使用cout获取ch地址?

重载parsingselectostream& operator<<(ostream& o, const char *c); 用于打印C风格的string。 你想要另一个ostream& operator<<(ostream& o, const void *p); 被选中。 在这里你可能是最好的select:

  cout << static_cast<void *>(cptr) << endl; 

cout打印一个string,如果它接收到一个char * ,那么简单。

这里是operator << for ostream的重载:

 ostream& operator<< (bool val); ostream& operator<< (short val); ostream& operator<< (unsigned short val); ostream& operator<< (int val); ostream& operator<< (unsigned int val); ostream& operator<< (long val); ostream& operator<< (unsigned long val); ostream& operator<< (float val); ostream& operator<< (double val); ostream& operator<< (long double val); ostream& operator<< (const void* val); ostream& operator<< (streambuf* sb); ostream& operator<< (ostream& ( *pf )(ostream&)); ostream& operator<< (ios& ( *pf )(ios&)); ostream& operator<< (ios_base& ( *pf )(ios_base&)); ostream& operator<< (ostream& out, char c ); ostream& operator<< (ostream& out, signed char c ); ostream& operator<< (ostream& out, unsigned char c ); //this is called ostream& operator<< (ostream& out, const char* s ); ostream& operator<< (ostream& out, const signed char* s ); ostream& operator<< (ostream& out, const unsigned char* s ); 

如果你想要的地址,你想要:

 ostream& operator<< (const void* val); 

所以你需要转换为const void*

我只是将它转换为void *,因此它不会将其解释为Cstring:

 cout << (void*) cptr << endl; 

然而,更安全的select是使用static_cast作为dirkgently的答案(这种方式至less在编译时检查)。

正如Luchian所说,cout根据types知道要打印什么。 如果你想打印指针值,你应该把指针指向void *,它将被分隔为一个指针。