有两个简单的类:
class X
{
int value;
public:
X() : value(0) {};
X(int v) : value(v) {};
X(const X& x) { // Does not help!
this->value = x.value;
}
X(const X&& x) noexcept { // Does not help!
this->value = x.value;
}
X& operator=(const X& right) {
this->value = right.value;
return *this;
};
X&& operator=(const X&& right) noexcept {
this->value = right.value;
return std::move(*this);
};
bool operator==(X& right) const {
return this->value == right.value;
};
};
class Y
{
int value;
public:
operator X() const {
return X(this->value);
}; // Y objects may be converted to X
};
并举例说明如何使用它:
int main()
{
X x1, x2;
Y y1;
x1 = x2; // Compiles
auto newv = (X)y1; // Compiles
x1 == newv; // Accepted!
x1 == (X)y1; // Error!!!
} // END: main()
x1 ==(X)y1行生成错误C2678:二进制'==':未找到采用'X'类型的左操作数的运算符(或没有可接受的转换)
并且“没有运算符==匹配这些操作数,操作数类型为X == X
我尝试使用C ++ 17进行编译。
如果像“ x1 == newv”这样的行对编译器有利,那怎么了?
bool operator==(X& right) const
应该是
bool operator==(const X& right) const
// ^^
否则,无法使用X
的临时(X)y1
对其进行调用。
另一个问题,与我的评论中的编译器错误无关:bool operator=(X& left) const
这是比较运算符==
还是赋值=
?函数声明是一个混合,实现是明显的比较。分配为X& operator=(const X& left) {value = left.value; return *this;}
。