【C++】<=>自动生成比较操作符

自定义类,若想要可以进行比较运算,需要重载6种操作符:==、!=、<、<=、>、>=

C++20起,operator<=>()可用于自定义类的6种比较操作符的自动生成。

#include <compare>
  • 返回类型

    std::strong_ordering
        //有less、greater、equivalent三种结果
    
  • default的<=>

    auto operator<=>(const Point& p) const = default;
    
    • default除了生成4个不等外,还会生成生成==,并由此自动生成!=
    • 自定义写的<=>,就不会自动生成==,需要自己手动写operator==()。编译器会基于你写的 == 再自动生成 !=
    • 只有当所有成员(及其父类)都支持<=>时,才可以写成default。
  • 默认比较规则:按照成员逐一比较

    • 自动生成<<=>>=(编译器基于<=>的结果)
    • 自动生成==!=(因为<=>default也会生成,从而编译器由取反得到!=)
    class Point
    {
    public:
        std::string str_;
        int x_;
        Point(std::string str, int x):str_(std::move(str)),x_(x){}
        auto operator<=>(const Point& p) const = default;
    }
    
    int main()
    {
        Point p1{"a", 1};
        Point p2{"b", 1};
        bool b1 = p1 == p2;
        bool b2 = p1 < p2;
    }
    
  • 自定义比较逻辑

    • 自定义 <=> 后,必须自己写 operator==,编译器会基于你写的 == 自动生成 !=
    class Point
    {
    public:
        std::string str_;
        int x_;
        Point(std::string str, int x):str_(std::move(str)),x_(x){}
        std::strong_ordering operator<=>(const Point& p) const
        {
            if(auto cmp = str_ <=> p.str_; cmp!=0)//str字典序比较,若不相等直接返回不等,若相等(==0)继续比较x_
                return cmp;
            return x_ <=> p.x_;
        }
        //自定义的<=>需要自己写提供operator==
        bool operator==(const Point& other)const
        {
            return str_==other.str_ && x_==other.x_;
        }
    }
    
    
    int main()
    {
        Point p1{"a", 1};
        Point p2{"b", 1};
        bool b1 = p1 == p2;
        bool b2 = p1 < p2;
    }
    
posted @ 2026-02-21 11:38  仰望星河Leon  阅读(3)  评论(0)    收藏  举报