重载运算符重载 [英] Overloading overloaded operators

查看:219
本文介绍了重载运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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() 函数。

这种编译器行为的原因是什么?

I have written the comments inside the main() function.
What's the reason for this sort of compiler's behavior?

此行为编译器是否依赖?

Is this behavior compiler dependent?

Linux上的GCC

GCC on Linux

推荐答案

你看到的行为是由const正确性引起的。运营商<<在类中定义的是非const的,所以它只能对非const对象或引用(如obj)进行操作。非类的成员版本有两个常量操作数。

The behavior you're seeing is caused by const-correctness. The operator<< defined within the class is non-const, so it can only operate on a non-const object or reference, such as obj. The non-member version outside the class has two constant operands.

如果您将成员版本编写为非成员,它将如下所示:

If you wrote the member version as a non-member, it would look like this:

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

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

When overload-matching, the compiler chooses the best fit. In the first case, the left operand is non-const, so it chooses the member operator. In the second case, the left operand is an rvalue (temporary binaryOperators), which is referenced as const, so the non-member operator is chosen.

这篇关于重载运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆