与其他数据类型的指针相比,为什么指向char的指针行为不同

时间:2013-03-27 10:13:21

标签: c++ pointers char

我对以下陈述表示怀疑;

int intvalue = 3;
int *pointInt = &intvalue;

char* p = "string";
cout << pointInt << std::endl;  // this will give memory location of intvalue which is ok.
cout << p<< std::endl; // why this will give string value  rather than memory location of where string is stored?

5 个答案:

答案 0 :(得分:5)

因为有overload of std::ostream& operator<<(std::ostream&, const char*),假设char*null-terminated string的第一个元素并打印出整个字符串。

通过尝试流式传输而不是以null结尾的字符串的第一个元素,您可以获得很多乐趣:

char*

答案 1 :(得分:3)

char*const char*最常用于指向C样式的以null结尾的字符串。标准I / O库在传递其中一种类型时要考虑到这一点,以便插入或提取。这些功能只是根据想要打印C风格字符串的常见情况而设计的。

要获取指针值,可以尝试转换为不同的指针类型:

std::cout << static_cast<void*>(p) << std::endl;

答案 2 :(得分:1)

关键字运算符重载 - 只是iostream实例的另一个方法std::cout负责不同的字符和句柄。确切的实现也可以产生“Hello World”

答案 3 :(得分:0)

cout << (void *) p << std::endl;

我希望这是因为<<运算符具有char*参数的特定覆盖,以输出字符串。

答案 4 :(得分:0)

对于作为第一个参数的cout对象的类型,这是operator<<()重载,并且键入char*const char*作为第二个参数。

有很多这样的重载,你也可以写一些。

这个特殊重载的原因是“打印”C风格的字符串(以null结尾的char数组)