【发布时间】:2020-07-26 17:33:30
【问题描述】:
我正在尝试理解 operator < 的运算符重载语法,其中第二个 const 单词需要编译器才能满意。
bool operator < (const point& rhs) const { // what's the rationale for the second const word here?
以struct为例
struct point {
int x;
int y;
point () : x(0), y(0) {}
point (int _x, int _y) : x(_x), y(_y) {}
point operator + (const point& rhs) {
return point(this->x + rhs.x, this->y + rhs.y);
}
bool operator < (const point& rhs) const {
return this->x < rhs.x;
}
};
这将允许我将其用作 mymap 的键。
map<point,int> mymap;
【问题讨论】:
-
第一个
const应用于参数 - 比较的右侧。第二个const适用于*this- 调用该方法的对象,恰好是比较的左侧。需要它的原因与需要第一个相同 - 能够比较两个const point对象。 -
+运算符也应该有第二个const。它不应该 - 也不应该 - 修改其左操作数 (*this)。顺便说一句,显示的代码中不需要任何this->子表达式。 -
@CiaPan,同意,不需要
this->。+运算符的第二个const对于编译器来说并不是必须的,这就是我的困惑所在。现在我再次尝试了,如果我不在 STLmap中使用point,那么第二个const不会破坏交易。所以,好吧,也许要在 STLmap中使用它必须是明确的。
标签: c++ oop overloading operator-keyword