从std::cout理解operator<<()

我为我的一位学生同事编写了这段小代码,以说明 C++ 中的重载:

#include <iostream>

int main() {
    std::cout << "Hello World!";
    std::cout.operator<<("Hello World!");
    return 0;
}

我天真地以为我会有两次“Hello World!”。但是第二行给我发了一个地址。我不明白为什么?

回答

根据cppreference(强调我的):

字符和字符串参数(例如,char 或 const char* 类型)由operator<<非成员重载处理。[...] 尝试使用成员函数调用语法输出字符串将调用重载 (7) 并改为打印指针值。

所以你的情况,调用成员operator<<确实将打印指针值,因为std::cout不具备过载const char*

相反,您可以operator<<像这样调用 free 函数:

#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;
}


以上是从std::cout理解operator&lt;&lt;()的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>