品牌网站建设S苏州,上海徐汇做网站,煤棚网架多少钱一平方,北京建筑网C20增加了三路比较运算符#xff08;戏称航天飞机运算符#xff09;#xff0c;用于对类的比较运算符进行统一的设计。有两种使用方式#xff1a;默认比较对于某些类#xff0c;如果按照其成员逐一比较即可决定比较运算符的值#xff0c;那么可以使用默认的三路运…C20增加了三路比较运算符戏称航天飞机运算符用于对类的比较运算符进行统一的设计。有两种使用方式默认比较对于某些类如果按照其成员逐一比较即可决定比较运算符的值那么可以使用默认的三路运算符编译器为为类生成,!,,,,#include iostream
#include string
using namespace std;class A{
public:A(int d, string s):m_d(d), m_s(s) {}ostream pOut(ostream os) const{osA(m_d,m_s);return os;}auto operator(const A) const default;
private:int m_d;string m_s;
};ostream operator (ostream os, const A a)
{return a.pOut(os);
}void doCompare(const A d1, const A d2)
{if(d1 d2){coutd1 is bigger than d2endl;}else if(d1 d2){coutd1 is equal to d2endl;}else if(d1 d2){coutd1 is smaller than d2endl;}
}int main()
{A a1(1, hi), a2(1, hello), a3(2, a);doCompare(a1, a2);doCompare(a1, a1);doCompare(a1, a3);return 0;
}运行程序输出A(1,hi) is bigger than A(1,hello)A(1,hi) is equal to A(1,hi)A(1,hi) is smaller than A(2,a)默认的比较运算符将按照成员的顺序先比较m_d然后再比较m_s如果将m_d与m_s定义的顺序反过来那么会影响到比较的结果#include iostream
#include string
using namespace std;class A{
public:A(int d, string s):m_d(d), m_s(s) {}ostream pOut(ostream os) const{osA(m_s,m_d);return os;}auto operator(const A) const default;
private:string m_s;int m_d;
};ostream operator (ostream os, const A a)
{return a.pOut(os);
}void doCompare(const A d1, const A d2)
{if(d1 d2){coutd1 is bigger than d2endl;}else if(d1 d2){coutd1 is equal to d2endl;}else if(d1 d2){coutd1 is smaller than d2endl;}
}int main()
{A a1(1, hi), a2(1, hello), a3(2, a);doCompare(a1, a2);doCompare(a1, a1);doCompare(a1, a3);return 0;
}运行程序输出A(hi,1) is bigger than A(hello,1)A(hi,1) is equal to A(hi,1)A(hi,1) is bigger than A(a,2)定制比较当默认的比较规则不合适时可以通过定义为类生成统一的比较运算符。定制比较时可以分为三个级别对应的返回值类型分别为返回类型是否有无法比较的值说明(强序)std::strong_ordering无所有元素都可比较且有严格的顺序关系可比较等值唯一比如数值(弱序)std::weak_ordering无所有元素都可比较但存在近似相等的情况可比较等值不唯一比如大小写字符(偏序)std::partial_ordering是元素存在不可比较的情况非全可比较等值也不唯一比如void*指针以下实现一个不区分大小写的字符串比较#include iostream
#include string
using namespace std;auto strToUpper [](string str)
{string s str;transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return toupper(c); });return s;
};class A{
public:A(string s):m_s(s) {}ostream pOut(ostream os) const{osA(m_s);return os;}weak_ordering operator(const A a) const{string sThis strToUpper(m_s);string sA strToUpper(a.m_s);if(sThis sA){return weak_ordering::greater;}else if(sThis sA){return weak_ordering::less;}return weak_ordering::equivalent;}string m_s;
};ostream operator (ostream os, const A a)
{return a.pOut(os);
}void doCompare(const A d1, const A d2)
{if(d1 d2){coutd1 is bigger than d2endl;}else if(d1 d2){coutd1 is smaller than d2endl;}else{coutd1 is equal to d2endl;}
}int main()
{A a1(hi), a2(hello), a3(Hi), a4(ho);doCompare(a1, a2);doCompare(a1, a3);doCompare(a1, a4);return 0;
}运行程序输出A(hi) is bigger than A(hello)A(hi) is equal to A(Hi)A(hi) is smaller than A(ho)可以看到通过实现了编译器会由此实现其他运算符。