我尝试操作符重载,为此,我下面的代码写包括常量给出错误(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;
}
};
在编译时,下面的错误显示
乐趣的.cpp(65):错误C2662: 'OwnClass ::的getX':不能 '这个' 从 '常量OwnClass' 指针转换为 'OwnClass &' 转化失去限定符
fun.cpp(66):错误C2662: 'OwnClass ::杰蒂':不能转换 从 'const的OwnClass' 到 'OwnClass &' 转换 '这个' 指针失去 限定符
当我修改代码作为下,它编译好。
OwnClass& operator + (OwnClass &o) // removed const
{
this->x += o.GetX();
this->y += o.GetY();
return *this;
}
我看不懂为什么这么说?我的意思是我无法理解编译器错误。
'operator +'应该返回一个新的对象,而不是同一个对象。它是'operator + ='应该返回当前对象(通过引用)。 – PaulMcKenzie
@PaulMcKenzie感谢您的额外信息! – SimpleGuy