6

在我的课堂上,我经常operator!=通过返回来快速写一篇文章!(*this == rhs),例如:

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

我看不出这样做有任何明显的问题,但我想我会问是否有人知道。

4

3 回答 3

11

我相信这是实现的首选方法,operator!=这样您就不会重复自己,并且您与operator==.

于 2009-01-12T19:20:35.517 回答
3

定义operator!=!operator==就好了

为了轻松定义这些琐碎的等效运算符,我总是使用Boost.Operators
仅使用operator==and的情况operator!=(即使用equal_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_;
   }

};
于 2009-01-12T20:03:36.880 回答
0

不,那绝对没问题——我也是这么做的。

于 2009-01-12T19:20:05.737 回答