【问题标题】:How does an operator inside a class work?类中的运算符如何工作?
【发布时间】:2017-03-16 20:28:25
【问题描述】:
class A {
public:
    string operator+( const A& rhs ) {
        return "this and A&";
    }
};

string operator+( const A& lhs, const A& rhs ) {
    return "A& and A&";
}

string operator-( const A& lhs, const A& rhs ) {
    return "A& and A&";
}

int main() {
    A a;
    cout << "a+a = " << a + a << endl;
    cout << "a-a = " << a - a << endl;
    return 0;
}

//output
a+a = this and A&
a-a = A& and A&

我很好奇为什么类内部的操作符被调用而不是外部的。运营商之间是否有某种优先级?

【问题讨论】:

  • 在多个同名函数中进行选择的过程称为重载解析。在此代码中,会员是首选,因为非会员需要资格转换(将const 添加到lhs)但会员不需要。如果你创建了成员函数const(你应该这样做,因为它不会修改*this),那么它会是模棱两可的

标签: c++ operator-overloading operators


【解决方案1】:

当你的对象是非常量时,非常量优先于常量。左边为非const时调用inner,左边为const时调用outer。

看看当内部定义为时会发生什么:

string operator+( const A&amp; rhs ) const;

【讨论】:

  • “非常量优先于常量。”一般情况下不会。如果 a 已声明为 const A a;,则将使用类外重载。
  • 这就是我写的。
  • 答案的写法是“非常量优先于常量”,这听起来像是一个笼统的陈述。这当然是不正确的。
【解决方案2】:

在多个同名函数中进行选择的过程称为重载解析。在此代码中,首选成员,因为非成员需要资格转换(将 const 添加到 lhs)但成员不需要。如果你创建了成员函数const(你应该这样做,因为它不会修改*this),那么它就会模棱两可。

【讨论】:

    猜你喜欢
    • 2016-10-25
    • 2020-01-29
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    • 1970-01-01
    相关资源
    最近更新 更多