c++ 类型转换 class 成员运算符问题
c++ type conversion class member operator issue
有两个简单的类:
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) { // Does not help!
this->value = right.value;
return *this;
};
X&& operator=(const X&& right) noexcept { // Does not help!
this->value = right.value;
return std::move(*this);
};
bool operator==(X& right) const {
return this->value == right.value;
};
};
class Y
{
int value;
public:
Y() : value(0) {};
operator X() const {
return X(this->value);
}; // Y objects may be converted to X
};
并举例说明我是如何使用它的:
int main()
{
X x1, x2;
Y y1;
x1 = x2; // Compiles (using the X& operator=)
x1 = std::move(x2); // Compiles (using the X&& operator=)
auto newv = (X)y1; // Compiles
x1 == newv; // Accepted!
x1 == (X)y1; // Error!!!
} // END: main()
x1 == (X)y1 行生成错误 C2678: binary '==': no operator found which takes a left-hand operand of type 'X' (or there are no acceptable conversion)
and "没有运算符==匹配这些操作数,操作数类型是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;}
.
有两个简单的类:
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) { // Does not help!
this->value = right.value;
return *this;
};
X&& operator=(const X&& right) noexcept { // Does not help!
this->value = right.value;
return std::move(*this);
};
bool operator==(X& right) const {
return this->value == right.value;
};
};
class Y
{
int value;
public:
Y() : value(0) {};
operator X() const {
return X(this->value);
}; // Y objects may be converted to X
};
并举例说明我是如何使用它的:
int main()
{
X x1, x2;
Y y1;
x1 = x2; // Compiles (using the X& operator=)
x1 = std::move(x2); // Compiles (using the X&& operator=)
auto newv = (X)y1; // Compiles
x1 == newv; // Accepted!
x1 == (X)y1; // Error!!!
} // END: main()
x1 == (X)y1 行生成错误 C2678: binary '==': no operator found which takes a left-hand operand of type 'X' (or there are no acceptable conversion)
and "没有运算符==匹配这些操作数,操作数类型是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;}
.