簡體   English   中英

我是否必須為一個類重載每個運算符以使其行為像其成員變量之一?

[英]Do I have to overload every operator for a class to behave like one of its member variables?

給定用戶定義的類型,如下所示:

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

確保我考慮字符串包含的每個重載操作,並將行為應用於字符串值。

我想說你最好的選擇是使用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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM