uni*_*uni 1 c++ spaceship-operator c++20
考虑使用默认比较稍微修改一下 cppreferenece.com 的示例:
struct Point
{
int x;
int y;
auto operator<=>(const Point&) const = default;
//bool operator!=(const Point&) const = default;
bool isDifferent(const Point& another) const
{
// Fails without explicit operator !=
return operator != (another);
}
bool isSame(const Point& another) const
{
// Always OK
return operator == (another);
}
};
int main()
{
Point pt1{1, 1}, pt2{1, 2};
std::cout << std::boolalpha
<< (pt1 == pt2) << ' ' // Always OK
<< (pt1 != pt2) << ' ' // Always OK
<< (pt1 < pt2) << ' '
<< (pt1 <= pt2) << ' '
<< (pt1 > pt2) << ' '
<< (pt1 >= pt2) << ' ';
}
Run Code Online (Sandbox Code Playgroud)
https://godbolt.org/z/dq56T3ssG
这里使用相等运算符的函数编译得很好。使用不等运算符的其他函数失败并出现“运算符未定义”错误。但是,如果不等式运算符在成员函数之外使用,则一切正常。
问题:为什么会发生这种情况?有没有办法不定义不等式运算符并在成员函数中使用它?
C++20 没有operator !=为你定义。它的作用是,当您使用!=运算符时,如果不operator !=存在匹配的函数(它比这更复杂,但现在没关系),它可以重写您的代码来调用operator ==并否定结果。并且operator ==是默认生成的实数函数operator <=>。
但是,您没有使用!=运算符。您要求调用名为 的函数operator !=。没有这样的功能,因此出现错误。
如果你想获得重写行为,你需要使用实际的!=运算符。
| 归档时间: |
|
| 查看次数: |
64 次 |
| 最近记录: |