2

在 C++20 中,如果我们使用 default <=>,那么还会添加所有其他比较运算符。
在代码中,该类有两个整数,因此要进行比较,则需要用户定义的比较。但由于相等运算符将自动生成,我需要知道它将如何比较对象。如果有复合类型会发生什么。

#include<compare>
#include<iostream>
using namespace std;
class Point {
    int x;
    int y;
public:
    Point(int x, int y):x(x),y(y){}
    friend strong_ordering operator<=>(const Point&, const Point&) = default;
};

int main()
{
    Point p(2,3), q(2,3);
    
    if(p==q) cout << "same" << endl;
    else cout << "different" << endl;

    return 0;
}
4

1 回答 1

3

任何类型的所有默认比较运算符都以相同的方式工作。它们按声明顺序逐个比较所有子对象(基类和成员),直到确定比较标准。

所以对于相等性测试,它测试Point::x,然后Point::y。但它会在xx相等时停止。

于 2021-02-07T15:11:24.997 回答