在操作符重载参数列表中包含const会产生错误(c++)

Including const in operator overloading argument list gives error (C++)

本文关键字:错误 c++ const 重载 操作符 参数 列表 包含      更新时间:2023-10-16

我正在尝试操作符重载,为此我编写了以下代码

class OwnClass
{
private:
    int x,y;
public:
    OwnClass(int x, int y) { SetX(x); SetY(y); }
    int GetX() { return x; }
    void SetX(int x) { this->x = x;}
    int GetY() { return y; }
    void SetY(int y) {this->y = y;}
    OwnClass& operator + (const OwnClass &o)  // Problematic line
    {
        this->x += o.GetX();
        this->y += o.GetY();
        return *this;
    }
};

编译时,显示以下错误

fun.cpp(65):错误C2662: 'OwnClass::GetX':无法转换'this'指针从'const OwnClass'指向'OwnClass &'转换失去限定符

fun.cpp(66):错误C2662: 'OwnClass::GetY':无法转换'this'指针从'const OwnClass'指向'OwnClass &'转换失败限定符

当我像下面这样修改代码时,它可以很好地编译。

OwnClass& operator + (OwnClass &o)  // removed const
{
    this->x += o.GetX();
    this->y += o.GetY();
    return *this;
}

我不能理解为什么?我的意思是我不能理解编译器错误

参数o声明为对const的引用,GetXGetY不能调用,因为它们是非const成员函数。你可以(也应该)把它们改成const成员函数来解决这个问题。

int GetX() const { return x; }
int GetY() const { return y; }

BTW:一般来说,二进制operator+不应该返回对非const的引用。最好按值返回一个新对象。

OwnClass operator + (const OwnClass &o) const
{
    OwnClass r(GetX(), GetY());
    r.x += o.GetX();
    r.y += o.GetY();
    return r;
}

注意在这种情况下,operator+也可以(也应该)声明为const成员函数。作为@M。M建议,把它改成非成员函数会更好。

问题是您在const对象上调用非const成员函数。让getter const来解决这个问题:

int GetX() const { return x; }
int GetY() const { return y; }