簡體   English   中英

為什么我不能在返回引用時使用 const?

[英]Why can't I use const when returning a reference?

為了完整起見,我也想為我提供一個簡單的一元+運算符。 我認為一元運算符應該是不可變的。 如果我讓operator-()返回否定的 object 的副本,則聲明-obj=other; objother都是Complex類型的對象)不會編譯。 但是,如果我讓operator+()返回 object 本身,另一個語句+obj=other; 將編譯。

問題是我不能在以下代碼段中使用const 錯誤是什么意思?

Complex& operator+() const
{
    return *this;
}

在此處輸入圖像描述

完整代碼

class Complex
{
private:
    double re;
    double im;

public:

    // others are intentionally removed for the sake of simplicity
    Complex operator-() const
    {
        return Complex{-re,-im};
    }
    Complex& operator+() const
    {
        return *this;
    }
}

您的運算符被標記為const因此*this is Complex const & 您的返回類型剝離const

通過聲明 function const ,您實際上給出了 promise 該操作不會更改對象的 state。

換句話說, this現在是一個 const 指針(又名指向常量數據的指針),因此通過取消引用它,您會得到一個const Complex& ,當您將該值分配給非 const 引用並因此錯誤時,它會被刪除。

您必須將代碼更改為:

const Complex& operator+() const {
    return *this;
}

When declaring a method with const , not only are you promising you won't touch any of the internal state of the object, you also promise that you will not return anything that can be used to change the internal state of the object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM