c++ - 重载重载运算符

标签 c++ gcc operator-overloading

#include <iostream>
#include <fstream>
using namespace std;

class binaryOperators 
{
    public:
        int i;

        binaryOperators (int tempI = 0)
        {
            i = tempI;
        }

        binaryOperators operator<< (const binaryOperators &right);
};

binaryOperators operator<< (const binaryOperators &left, const binaryOperators &right)
{
    cout << "\nOne";
    return left;
}

binaryOperators binaryOperators :: operator<< (const binaryOperators &right)
{
    cout << "\nTwo";
    return *this;
}

int main ()
{   
    binaryOperators obj;

    // Compiler's behavior: This statement calls the overloaded operator << declared inside the class.
    obj << 5 << 3 << 2;
    // Compiler's behavior: This statement calls the overloaded operator << declared outside the class.
    2 << obj;

    return 0;
}

我在 main() 函数中写了注释。
这种编译器行为的原因是什么?

此行为是否依赖于编译器?

Linux 上的 GCC

最佳答案

您看到的行为是由常量正确性引起的。类内部定义的operator<<是非常量的,所以它只能对非常量对象或引用进行操作,比如obj。类外的非成员版本有两个常量操作数。

如果你把成员(member)版写成非成员(member),会是这样的:

binaryOperators operator<< (binaryOperators &left, const binaryOperators &right)
{
    cout << "\nTwo";
    return left;
}

重载匹配时,编译器会选择最合适的。在第一种情况下,左操作数是非常量,因此它选择成员运算符。在第二种情况下,左操作数是一个右值(临时 binaryOperators),它被引用为 const,因此选择了非成员运算符。

关于c++ - 重载重载运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8710290/

相关文章:

c++ - 是否建议在函数中使用 using 关键字?

c - 如何获取 gcc 的 Ada 规范搜索路径

gcc - 在启用 AESNI 内在函数的情况下调用 _mm_loadu_si128() 失败

c++ - undefined symbol "_ThreadRuneLocale"

c++ - 运算符重载示例不清楚

C++ 重载运算符 << 用于 std::string

c++ - 了解 C++ 中的运算符重载

C++ 错误 "invalid constructor; your probably meant ' 帐户(常量帐户&)

c++ - 如何在 C++ 中初始化双指针结构数组?

C++ 强化学习和智能指针