C++ 在运算符重载参数列表中包含常量会导致错误(C+;+;)

C++ 在运算符重载参数列表中包含常量会导致错误(C+;+;),c++,polymorphism,operator-overloading,operator-keyword,C++,Polymorphism,Operator Overloading,Operator Keyword,我正在尝试运算符重载,为此我编写了以下代码 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 =

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

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”:无法转换 “此”指针从“const OwnClass”到“OwnClass&”的转换丢失 限定词

当我像下面那样修改代码时,它编译得很好

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

    return *this;
}

我不明白为什么会这样?我的意思是我不能理解编译器错误。

参数
o
被声明为引用
const
,不能用
GetX
GetY
调用,因为它们是非常量成员函数。您可以(也应该)将它们更改为常量成员函数以解决此问题

int GetX() const { return x; }
int GetY() const { return y; }
顺便说一句:一般来说,二进制
运算符+
不应该返回对非常量的引用。最好按值返回一个新对象

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

    return r;
}

注意:对于这种情况,
运算符+
也可以(而且应该)声明为常量成员函数。正如@M.M所建议的,使其成为非成员函数会更好。

参数
o
被声明为引用
const
,不能用
GetX
GetY
调用,因为它们是非成员函数。您可以(也应该)将它们更改为常量成员函数以解决此问题

int GetX() const { return x; }
int GetY() const { return y; }
顺便说一句:一般来说,二进制
运算符+
不应该返回对非常量的引用。最好按值返回一个新对象

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

    return r;
}

注意:对于这种情况,
运算符+
也可以(而且应该)声明为常量成员函数。正如@M.M所建议的,使其成为非成员函数会更好。

问题是您正在对
const
对象调用非常量成员函数。使getter
const
修复此问题:

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

问题是您正在对
const
对象调用非常量成员函数。使getter
const
修复此问题:

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

operator+
应该返回一个新对象,而不是同一个对象。应该是
operator+=
返回当前对象(通过引用)。@PaulMcKenzie感谢您提供的附加信息<代码>运算符+应返回一个新对象,而不是同一个对象。应该是
operator+=
返回当前对象(通过引用)。@PaulMcKenzie感谢您提供的附加信息!哦我怎么会错过这个。。谢谢哦我怎么会错过这个。。谢谢哦我怎么会错过这个。。谢谢哦我怎么会错过这个。。谢谢