【问题标题】:Understanding operator overloading 'const' syntax for use in STL map了解在 STL 映射中使用的运算符重载“const”语法
【发布时间】: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-&gt; 子表达式。
  • @CiaPan,同意,不需要this-&gt;+ 运算符的第二个 const 对于编译器来说并不是必须的,这就是我的困惑所在。现在我再次尝试了,如果我不在 STL map 中使用 point,那么第二个 const 不会破坏交易。所以,好吧,也许要在 STL map 中使用它必须是明确的。

标签: c++ oop overloading operator-keyword


【解决方案1】:

方法声明末尾的外部const 告诉编译器该方法的*this 对象将是const

std::map 将其键存储为 const 值。所以任何应用于键的运算符都需要标记为const,否则它们将无法编译。 std::map 默认使用 operator&lt; 对其键进行排序并比较它们是否相等。

此外,作为一种良好做法,任何不修改*this 内容的成员方法/运算符无论如何都应标记为const。这样做可以让用户知道此类操作是只读的,并让编译器在 const 对象的表达式中使用它们。

【讨论】:

    【解决方案2】:

    末尾的const 表示该函数不会更改调用它的对象。这允许在 const 对象上调用函数。

    【讨论】:

      【解决方案3】:

      第二个const 是隐含参数this 指向的对象的限定符。这意味着不允许该方法修改其对象。事实上,比较不需要——也不应该——修改被比较的对象。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-01
        • 1970-01-01
        • 2012-11-19
        • 2017-06-14
        • 2014-11-07
        • 1970-01-01
        • 2010-09-13
        • 1970-01-01
        相关资源
        最近更新 更多