2009-01-12 65 views
7

在我的課,我經常通過返回!(*this == rhs)編寫一個快速operator!=,如:快速和骯髒的運營商=

class Foo 
{ 
private: 
    int n_; 
    std::string str_; 
public: 
    ... 
    bool operator==(const Foo& rhs) const 
    { 
     return n_ == rhs.n_ && str_ == rhs.str_; 
    } 

    bool operator!=(const Foo& rhs) const 
    { 
     return !(*this == rhs); 
    } 
}; 

我不能看到這樣做的任何明顯的問題,但認爲我會問,如果任何人知道任何。

+0

+1還是喜歡操作符重載,而不是ISEQUAL(ObjA,ObjB)。我覺得這很整潔 – Perpetualcoder 2009-01-12 19:25:22

回答

11

我相信這是實施operator!=的首選方法,這樣您就不會重複自己,並保證與operator==的正確關係。

0

不,這絕對沒問題 - 我也一樣。

2

定義operator!=!operator==就好了

爲了得到這些瑣碎相當於運營商容易界定,我總是用Boost.Operators
只有operator==operator!=(即使用equality_comparable<>)的情況沒有太大收益。

但是,當你需要更少和更大的,或operator+,operator*等的一些組合,這變得非常方便。

您的情況的一個例子會讀

class Foo : private boost::equality_comparable<Foo> 
{ 
    private: 
    int n_; 
    std::string str_; 
    public: 
    ... 
    bool operator==(const Foo& rhs) const 
    { 
     return n_ == rhs.n_ && str_ == rhs.str_; 
    } 

};