3 回答
TA贡献1869条经验 获得超4个赞
重载分辨率选择ostream& operator<<(ostream& o, const char *c);用于打印C样式字符串的。您要ostream& operator<<(ostream& o, const void *p);选择另一个。您可能最好在这里进行演员表:
cout << static_cast<void *>(cptr) << endl;
TA贡献1887条经验 获得超5个赞
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*。
TA贡献1863条经验 获得超2个赞
我只是将其转换为void *,因此它不会尝试将其解释为C字符串:
cout << (void*) cptr << endl;
但是,一个更安全的选择是使用dirkgently的答案中的static_cast(这样,至少在编译时检查了强制类型转换)。
- 3 回答
- 0 关注
- 613 浏览
添加回答
举报