为什么流式字符指针来清点无法打印的地址?为什么流式字符指针来清点无法打印的地址?(Why does

2019-05-17 00:22发布

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.

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;
}

Here, in my GNU compiler, cout is trying to output ch as a string.

How I can get address of ch via cptr using cout?

Answer 1:

重载解析选择ostream& operator<<(ostream& o, const char *c); 这是用于打印C风格的字符串。 你想其他ostream& operator<<(ostream& o, const void *p); 被选择。 你可能是最好关闭在这里铸造:

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


Answer 2:

cout打印字符串,如果它收到一个char * ,就这么简单。

下面是重载operator <<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*



Answer 3:

我只是将它转换为一个void *,因此不会尝试把它解释为一个C字符串:

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

然而,一个更安全的选择是使用的static_cast在dirkgently的答案(这样的投至少在编译期进行检查)。



Answer 4:

作为Luchian说,COUT知道要打印的基础的类型是什么。 如果你想打印指针值,你应该转换指针为void *将被interpated为指针。



文章来源: Why does streaming a char pointer to cout not print an address?