首页 > 解决方案 > c++中关于const成员函数的问题

问题描述

谁能解释我这个错误?这是代码:

class O{
    unsigned x;
    unsigned y;
    public:
        O(unsigned x_ ,unsigned  y_): x(x_), y(y_){
        };
        O& operator+= ( O & object){
            x += object.x;
        }
};

class A {
    O item;
    public:
        A(O i): item(i){;
        }
        void fun() const{
            O j(2,3);
            j += item;
        }
};

int main(){
    return 0;
}

当我尝试编译时,出现此错误:

In member function 'void A::fun() const':
[Error] no match for 'operator+=' (operand types are 'O' and 'const O')
[Note] candidate is:
[Note] O& O::operator+=(O&)
[Note] no known conversion for argument 1 from 'const O' to 'O&'

谁能给我解释一下?如果我将 const 限定符添加到 += 运算符的参数,它会编译。所以我认为问题在于我在 const 函数 fun() 中将对 item 的引用传递给 += 运算符,它是非 const。谁能解释我为什么这是非法的,以及我如何避免犯这种错误,例如,如果在使用 const 限定符等时有一些经验法则可以遵循?

标签: c++classreferenceconstantsconst-reference

解决方案


这个成员函数

  void fun() const{
        O j(2,3);
        j += item;
    }

是一个常数成员函数。因此,调用函数的对象的成员被视为常量成员,特别是在这种情况下,数据成员项被视为声明为

const O item;

在这个表达式中

j += item;

有使用成员函数

    O& operator+= ( O & object){
        x += object.x;
    }

它接受对 O 类型对象的非常量引用。因此,实际上您正在尝试将非常量引用绑定到常量对象。所以编译器发出错误。

上述运算符的参数应使用限定符 const 声明,并具有 return 语句,例如

    O& operator+= ( const O & object) {
        x += object.x;
        return *this;
    }

推荐阅读