c++ - 从std::cout了解运算符<<()

标签 c++

我已经为我的一个学生同事编写了这个小代码,以说明c++中的重载:

#include <iostream>

int main() {
    std::cout << "Hello World!";
    std::cout.operator<<("Hello World!");
    return 0;
}
我天真地想我会两次获得“Hello World!”。但是第二行给我发了一个地址。我不明白为什么?

最佳答案

根据cppreference(重点是我的):

Character and character string arguments (e.g., of type char or const char*) are handled by the non-member overloads of operator<<. [...] Attempting to output a character string using the member function call syntax will call overload (7) and print the pointer value instead.


因此,在您的情况下,调用operator<<成员确实会打印指针值,因为std::cout并没有const char*的重载。
相反,您可以像下面这样调用免费函数operator<<:
#include <iostream>
int main() {
    std::cout << "Hello World!";           //prints the string
    std::cout.operator<<("Hello World!");  //prints the pointer value
    operator<<(std::cout, "Hello World!"); //prints the string
    return 0;
}

关于c++ - 从std::cout了解运算符<<(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66275035/

相关文章:

c++ - 在 Visual Studio dissembly 窗口中添加了额外的 C++ 括号?

c++ - char[5] 和 char[10] 有什么区别?

c++ - 我怎样才能让 QThread 在不泄漏的情况下发出堆分配的 QObject?

C++ 缓冲区太小错误

c++ - Arduino unsigned long int 到 char*

c++ - Qt 无法解析项目文件

c++ - 究竟什么是声音引擎?

c++ - 使用对 vector 时出现无效、错误的数字模板参数错误

c++ - 有什么工具可以帮助我阅读 c++ 模板编译错误吗?

c++ - 解析 Google Protocol Buffer 的文本文件