这与 difference-between-cout-x-and-cout-operator-x 有关问题,但还是有点不同...
#include <iostream>
int main(){
std::cout << "hello" << std::endl;
std::cout.operator<<("hello2");
std::cout.operator<<(std::endl);
operator<<(std::cout, "hello3");
// operator<<(std::cout, std::endl);
return 0;
}
Q1:为什么std::cout.operator<<("hello2");
工作?
来自 other answers所以我希望编译器会提示 operator<<
是一个免费功能,而不是 cout
的成员.然而,在我的系统上,它打印出“0x10d54df31”。而且,更奇怪的是,以下行正确地执行了 std::endl
.
Q2:为什么operator<<(std::cout, std::endl);
不工作?
我知道 std::endl
是一个函数,但 hello3 输出起作用而 `std::endl' 不起作用,这对我来说似乎很奇怪。相反,编译器会抛出一个错误:
main.cpp:10:4: error: no matching function for call to 'operator<<'
operator<<(std::cout, std::endl);
Q3:第一个std::cout << "hello1" << std::endl;
怎么可以写在operator<<(...)
形式?
如果回答了前两个问题,那么这可能已经涵盖了。这是本次学习练习的重点,因此明确提出问题似乎是明智的。
最佳答案
运算符可以用不同的方式实现,特别是 operator<<
左侧是您的类型的可以实现为自由函数或该左侧类型的成员函数。
虽然您必须实现 ostream& operator<<(ostream&, MyType const&)
作为自由函数(因为 MyType
不是左侧),库实现可以选择* 来实现 operator<<
对于一些基本类型,插入 std::ostream
类型(这实际上是模板的特定实例,我试图忽略细节)。
编辑:根据标准检查后这是不正确的:
这就是您在代码中注意到的,采用 const char*
的重载作为 ostream
的成员实现( basic_ostream<char,char_traits<char>
).罢工>
采用操纵器的重载实现为成员函数 (Q2),并且存在从 const char*
的隐式转换至 const void*
如果您使用显式调用成员运算符 (Q1) 的语法,则会选择它。对于 Q3,答案是:
operator<<(std::cout, "Hello").operator<<(std::endl);
* 实现实际上不是自由选择的,因为标准强制要求签名。
关于c++ - `cout << x` 和 `cout.operator<<(x)` 和 `operator(std::cout, x)` 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20888009/