gpt4 book ai didi

c++ - 为什么char数据的地址不显示?

转载 作者:行者123 更新时间:2023-11-30 17:31:20 26 4
gpt4 key购买 nike

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 - some 始终等于 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;

关于c++ - 为什么char数据的地址不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24675585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com