在操作符重载参数列表中包含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
的引用,GetX
和GetY
不能调用,因为它们是非const成员函数。你可以(也应该)把它们改成const成员函数来解决这个问题。
int GetX() const { return x; }
int GetY() const { return y; }
BTW:一般来说,二进制operator+
不应该返回对非const的引用。最好按值返回一个新对象。
OwnClass operator + (const OwnClass &o) const
{
OwnClass r(GetX(), GetY());
r.x += o.GetX();
r.y += o.GetY();
return r;
}
注意在这种情况下,operator+
也可以(也应该)声明为const成员函数。作为@M。M建议,把它改成非成员函数会更好。
问题是您在const
对象上调用非const成员函数。让getter const
来解决这个问题:
int GetX() const { return x; }
int GetY() const { return y; }
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 错误:未在此范围内声明'reverse'