我最近注意到一些我自己无法弄清楚的运算符重载行为。以下两个类仅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