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

why pointer to char behaves differently as compared to pointersof other data types

本文关键字:指针 其他 char 为什么 数据类型      更新时间:2023-10-16

我对以下陈述有疑问;

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?

因为存在 std::ostream& operator<<(std::ostream&, const char*) 的重载,它假定char*是以 null 结尾的字符串的第一个元素并打印出整个字符串。

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

#include <iostream>
int main()
{
  char c = 'x';
  std::cout << &c << std::endl;
}

char*const char*最常用于指向以 C 样式的 null 结尾的字符串。标准 I/O 库在传递要插入或提取到的类型之一时会考虑到这一点。这些函数只是根据想要打印出 C 样式字符串的常见程度来设计为具有这种特殊情况。

若要获取指针值,可以尝试强制转换为其他指针类型:

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

关键字运算符重载 - 只是iostream实例的另一种方法,std::cout负责字符并以不同的方式处理。确切的实现也可以产生"Hello World">

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

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

这是

operator<<() cout 对象的类型作为第一个参数并将类型char*const char*作为第二个参数的重载。

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

这种特殊重载的原因是"打印"C 样式字符串(以 null 结尾的字符数组(