我需要为一个类重载所有运算符才能使其行为像其成员变量吗?

9

假设我们有一个用户定义的类型,如下所示:

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;
};

我需要确保考虑到字符串中的每个重载操作,并将该行为应用于字符串值。


这只是为了比较你类中的“word”吗? - user1810087
1
好的,你可以给它一个转换运算符,但那并不完美。 - chris
@itwasntpete 是的,在进行关系比较时,应该忽略小部件。 - Trevor Hickey
@chris 这个方法有什么缺点吗?我可能会不小心将它传递给一个需要字符串的函数吗?但是这种方法仍然可以让我只使用一个重载来进行所有关系比较,对吗? - Trevor Hickey
1
根据您的设计,您可以继承自std :: string。 - user1810087
@TrevorHickey,这种情况比你想象的要经常发生:http://coliru.stacked-crooked.com/a/ed6b123120892e92 - chris
1个回答

8

我认为你最好使用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>

我所要做的就是包含“utility”并实现这两种方法吗? - Trevor Hickey
基本上,我将更新答案以包括boost运算符,这基本上是类似于relops的“类固醇”版本。 - aaronman
@TrevorHickey 你还需要执行 using namespace std::rel_ops - aaronman
@C.R. C++充满了魔力,如果你真的想看到一些东西,就去查一下CRTP。 - aaronman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接