为什么在返回引用时不能使用const?
为了完整起见,我还想为我提供一个简单的一元运算+符。我认为一元运算符应该是不可变的。如果我做operator-()回了否定对象的副本,声明-obj=other;(包括obj和other是类型的对象Complex),将无法编译。但是,如果我operator+()返回对象本身,+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为*thisis Complex const &。您的返回类型将删除const.