简体   繁体   中英

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

For the sake of completeness, I want to provide me with a trivial unary + operator as well. The unary operators should be immutable, I think. If I make operator-() return a copy of the negated object, a statement -obj=other; (both obj and other are objects of type Complex ) will not compile. However, if I make operator+() return the object itself, another statement +obj=other; will compile.

The problem is I cannot use const in the following snippet. What does the error mean?

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

在此处输入图像描述

Complete Code

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

You operator is marked const thus the *this is Complex const & . Your return type strips the const .

By declaring the function const , you in fact give a promise that this operation won't change the object's state.

In other words, this is now a const pointer ( aka a pointer to constant data ), and thus by dereferencing it you get a const Complex& , something which is dropped when you assign that value to a non-const reference and thus the error.

You have to change your code to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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