我已经为我的一个学生同事编写了这个小代码,以说明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/