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 ;
}
输出为:
address of int : something
address of char : // nothing, blank area, that is nothing displayed
address of string : something
为什么?
另一个有趣的事情:如果int,char,string是公共(public)的,则输出为
... int : something
... char :
... string : something_2
something_2 - something
始终等于8。为什么? (不是9) 最佳答案
当您使用b的地址时,您会得到char *
。 operator<<
将其解释为C字符串,并尝试打印一个字符序列而不是其地址。
请尝试cout << "address of char :" << (void *) &b << endl
。
[编辑]就像Tomek所评论的那样,在这种情况下更适合使用的强制转换是static_cast
,这是一种更安全的选择。这是使用它而不是C样式强制转换的版本:
cout << "address of char :" << static_cast<void *>(&b) << endl;