简体   繁体   English

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

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

I am trying out with operator overloading, for which I wrote below code 我正在尝试使用运算符重载,为此我在下面的代码中进行了编写

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;
    }
};

When compiled, following error is shown 编译时,显示以下错误

fun.cpp(65): error C2662: 'OwnClass::GetX' : cannot convert 'this' pointer from 'const OwnClass' to 'OwnClass &' Conversion loses qualifiers fun.cpp(65):错误C2662:'OwnClass :: GetX':无法将'this'指针从'const OwnClass'转换为'OwnClass&'转换丢失了限定符

fun.cpp(66): error C2662: 'OwnClass::GetY' : cannot convert 'this' pointer from 'const OwnClass' to 'OwnClass &' Conversion loses qualifiers fun.cpp(66):错误C2662:'OwnClass :: GetY':无法将'this'指针从'const OwnClass'转换为'OwnClass&'转换丢失了限定符

When I modify the code as under, it compiles fine. 当我如下修改代码时,它可以正常编译。

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

    return *this;
}

I could not understand why so ? 我不明白为什么会这样? I mean I am not able to understand the compiler error. 我的意思是我无法理解编译器错误。

The parameter o is declared as reference to const , which can't be called with GetX and GetY , because they're non-const member function. 参数o被声明为对const引用,不能用GetXGetY调用它们,因为它们是非const成员函数。 You can (and should) change them to const member functions to solve the issue. 您可以(并且应该)将它们更改为const成员函数以解决此问题。

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

BTW: In general binary operator+ is not supposed to return a reference to non-const. 顺便说一句:通常,二进制operator+不应返回对非const的引用。 It's better to return a new object by value. 最好按值返回一个新对象。

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

    return r;
}

Note for this case operator+ could (and should) be declared as const member function too. 请注意,在这种情况下, operator+也可以(并且应该)声明为const成员函数。 And as @MM suggested, making it non-member function would be better. 就像@MM建议的那样,使其成为非成员函数会更好。

The problem is that you are calling non-const member functions on const objects. 问题是您要在const对象上调用非const成员函数。 Make getters const to fix this problem: 使getters const可解决此问题:

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

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

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