小编Sim*_*onT的帖子

C++ 比较运算符重载常量与非常量行为

我最近注意到一些我自己无法弄清楚的运算符重载行为。以下两个类仅const在 的成员比较运算符重载上有所不同ClassA。在ClassB他们没有const的。一般来说,我知道人们总是更喜欢那个const,但我仍然对为什么我们会看到我将在下面描述的行为感兴趣。

#include <string>

class ClassA {
public:
    explicit ClassA(double t) : _t(t) {}

    std::string operator<=(int const& other) const {
        return "A(<=)";
    }

    std::string operator==(int const& other) const {
        return "A(==)";
    }

    friend std::string operator<=(int const& other, ClassA const& expr) {
        return "A'(<=)";
    }

    friend std::string operator==(int const& other, ClassA const& expr) {
        return "A'(==)";
    }

private:
    double _t;
};

class ClassB {
public:
    explicit ClassB(double t) : _t(t) {}

    std::string operator<=(int …
Run Code Online (Sandbox Code Playgroud)

c++ compiler-errors operator-overloading language-lawyer c++20

5
推荐指数
1
解决办法
112
查看次数