【发布时间】:2021-05-11 08:02:19
【问题描述】:
在 C++20 中,如果我们使用默认的 <=>,那么所有其他的比较运算符也会被添加。
在代码中,该类有两个整数,因此要进行比较,则需要用户定义的比较。但由于相等运算符将自动生成,我需要知道它将如何比较对象。如果有复合类型会发生什么。
#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;
}
【问题讨论】:
-
“可能会生成”是什么意思?它比较所有成员是否相等,不是吗?
-
那么,它会比较每个成员吗?
-
默认比较运算符 - en.cppreference.com/w/cpp/language/default_comparisons "...默认运算符 通过依次比较基数(从左到右深度优先)然后非静态成员(按声明顺序)要计算的 T 子对象 ,递归扩展数组成员(按下标递增的顺序),并在发现不相等的结果时提前停止,..."跨度>
标签: c++ c++20 equality-operator