简体   繁体   English

重载 operator+ 两次(在类内和类外)

[英]overloading operator+ twice (inside and outside class)

Why am I allowed to do this, why there is no ambiguity complain, and why is the class' method chosen with prior to the other one?为什么允许我这样做,为什么没有模棱两可的抱怨,为什么选择类的方法先于另一个?

class EX
{
public:
    //...

    void operator+(const EX& ref)
    {
        cout << "A";
    }
};

void operator+(const EX& ref1, const EX& ref2)
{
    cout << "B" << endl;
}

int main()
{
    EX obj1{20};
    EX obj2{30};


    cout << "obj1 + obj2 = " <<  obj1 + obj2 << endl;

    return 0;
}

I was expecting the global function operator+ to be called an "B" printed on the screen, instead "A" was printed.我期待全局 function operator+被称为打印在屏幕上的"B" ,而不是打印"A"

Your member overload accepts only non-const instances of EX for the first operand while the free overload accepts both const and non-const instances.您的成员重载仅接受第一个操作数的EX的非常量实例,而自由重载同时接受 const 和非常量实例。 By overload resolution rules, the non-const wins out because it exactly matches the type being passed in.通过重载解析规则,非常量会胜出,因为它与传入的类型完全匹配。

You'll get an ambiguity error if you make the member overload const, indicating that *this is const:如果你让成员重载 const,你会得到一个模棱两可的错误,表明*this是 const:

void operator+(const EX& ref) const
{
    cout << "A";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM