[英]understanding the operator<<() from std::cout
我为我的一位学生同事编写了这个小代码,以说明 c++ 中的重载:
#include <iostream>
int main() {
std::cout << "Hello World!";
std::cout.operator<<("Hello World!");
return 0;
}
我天真地以为我会有两次“Hello World”。 但是第二行给我一个地址? 我不明白为什么?
根据cppreference (强调我的):
字符和字符串 arguments(例如,char 或 const char* 类型)由operator<< 的非成员重载处理。 [...] 使用成员 function 调用语法尝试 output 字符串将调用重载(7)并打印指针值。
因此,在您的情况下,调用成员operator<<
确实会打印指针值,因为std::cout
没有const char*
的重载。
相反,您可以像这样调用免费的 function 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;
}
如果操作员是成员 function 则
object operator other_operand
相当于
object.operator(other_operand)
但是,如果操作员不是成员,那么它是
operator(object,other_operand)
在这里您可以找到成员<<
://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt的重载列表
这里是非成员的重载列表https://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt2
请注意, char*
的operator<<
不是成员! 但是有一个成员operator<<
for void*
可以打印任何类型的指针的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.