c++ - 为什么 'operator<<(cout, double)' 不起作用?

标签 c++ operators overloading operator-keyword

我正在研究重载运算符。 我不明白使用 << 之间的区别-double 上的运算符(operator)/一个 std::string .

int main()
{
    double a = 12;
    string s = "example";

    operator<<(cout, a); //doesn't work
    cout.operator<<(a);  //works

    operator<<(cout, s); //works
    cout.operator<<(s);  //doesn't work   
}    

为什么不是 operator<<(cout, a)cout.operator<<(s);工作?

最佳答案

因为该运算符被定义为成员函数,而不是自由函数。

运算符可以通过这两种方式重载,当与常规运算符语法一起使用时,这对用户来说是透明的。但是,当使用显式语法时,您必须使用特定于实际函数定义的语法。

此示例显示了实践中的差异:

class Stream {
    Stream& operator<<(Inside);
};

Stream& operator<<(Stream&, Outside);

对于std::string,使用了Outside方式。对于 doubleInside 是。

关于c++ - 为什么 'operator<<(cout, double)' 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57076834/

相关文章:

c++ - 按返回类型重载

c++ - 重载 + 运算符以组合两个使用 vector 的字典

c# - C#、C/C++ 或 Objective-C 中的眼动追踪库

c - 使用 c 语法构建 ast 时管理操作优先级

python - 理解Python中的这个类。运算符 % 和格式化 float

c++ - 具有重写运算符的模板类

java - Java 中使用泛型进行函数重载

c++ - 正则表达式匹配组提升 C++

c++ - Qt 5.1.1 with Visual Studio 2012 - 这些 QT 版本不可访问

c++ - 即使在使用 delete[] 时调试断言失败