我是否必须为一个类重载每个运算符以使其行为像其成员变量之一?

 骚扰list_238 发布于 2023-02-13 15:00

给定用户定义的类型,如下所示:

struct Word{
    std::string word;
    Widget widget;
};

有没有办法让这个类的每个重载运算符表现得完全一样,就像它只是一个字符串一样?或者我必须通过以下方式实现该类:

struct Word{

    bool operator < (Word const& lhs) const;
    bool operator > (Word const& lhs) const;
    bool operator <= (Word const& lhs) const;
    bool operator => (Word const& lhs) const;
    bool operator == (Word const& lhs) const;
    bool operator != (Word const& lhs) const;
    //etc...

    std::string word;
    Widget widget;
};

确保我考虑字符串包含的每个重载操作,并将行为应用于字符串值.

1 个回答
  • 我想说你最好的选择就是使用std::rel_ops你只需要实现的方式==,<并获得所有这些功能.这是cppreference的一个简单示例.

    #include <iostream>
    #include <utility>
    
    struct Foo {
        int n;
    };
    
    bool operator==(const Foo& lhs, const Foo& rhs)
    {
        return lhs.n == rhs.n;
    }
    
    bool operator<(const Foo& lhs, const Foo& rhs)
    {
        return lhs.n < rhs.n;
    }
    
    int main()
    {
        Foo f1 = {1};
        Foo f2 = {2};
        using namespace std::rel_ops;
    
        std::cout << std::boolalpha;
        std::cout << "not equal?     : " << (f1 != f2) << '\n';
        std::cout << "greater?       : " << (f1 > f2) << '\n';
        std::cout << "less equal?    : " << (f1 <= f2) << '\n';
        std::cout << "greater equal? : " << (f1 >= f2) << '\n';
    }  
    

    如果你需要更完整版本的这种类型的东西使用 <boost/operators.hpp>

    2023-02-13 15:02 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有