问题描述
class Address {
int i;
char b;
string c;
public:
void showMap(void);
};
void Address :: showMap(void){
cout< address of int:<< & i< endl;
cout<< 地址char:< & b< endl;
cout<< string of string:<< & c< endl;
}
输出为:
地址int:something
char的地址://没有,空白区域,没有显示
字符串地址:something
为什么?
事情:如果int,char,string是在public,那么输出是
... int:something
... char:
... string:something_2
something_2 - something
总是等于8. 为什么? (不是9)解决方案当您使用b的地址时, char * 。
运算符<<
将其解释为C字符串,并尝试打印字符序列而不是其地址。
try
cout<< 地址char:< (void *)& b<
像Tomek所说,在这种情况下使用更合适的转换是
static_cast
,这是一个更安全的替代品。这是一个使用它而不是C风格的转换的版本:cout< 地址char:< static_cast< void *>(& b)<< endl;
class Address { int i ; char b; string c; public: void showMap ( void ) ; }; void Address :: showMap ( void ) { cout << "address of int :" << &i << endl ; cout << "address of char :" << &b << endl ; cout << "address of string :" << &c << endl ; }
The output is:
address of int : something address of char : // nothing, blank area, that is nothing displayed address of string : something
Why?
Another interesting thing: if int, char, string is in public, then the output is
... int : something ... char : ... string : something_2
something_2 - something
is always equal to 8. Why? (not 9)解决方案When you are taking the address of b, you get
char *
.operator<<
interprets that as a C string, and tries to print a character sequence instead of its address.try
cout << "address of char :" << (void *) &b << endl
instead.[EDIT] Like Tomek commented, a more proper cast to use in this case is
static_cast
, which is a safer alternative. Here is a version that uses it instead of the C-style cast:cout << "address of char :" << static_cast<void *>(&b) << endl;
这篇关于为什么不显示字符数据的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!