簡體   English   中英

在運算符重載參數列表中包含const會導致錯誤(C ++)

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

我正在嘗試使用運算符重載,為此我在下面的代碼中進行了編寫

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

順便說一句:通常,二進制operator+不應返回對非const的引用。 最好按值返回一個新對象。

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

    return r;
}

請注意,在這種情況下, operator+也可以(並且應該)聲明為const成員函數。 就像@MM建議的那樣,使其成為非成員函數會更好。

問題是您要在const對象上調用非const成員函數。 使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