在我的课我常常写一个快速 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);
    }
};

我看不到任何明显的问题有这样做,但我想问,如果有人知道的任何。

有帮助吗?

解决方案

我相信这是实现operator!=让你不重复自己的首选方法,和你有operator==保证正确的关系。

其他提示

定义 operator!= 作为 !operator== 是就好了

为获得这些琐碎的同等经营者容易地定义,我总是用 提升。运营商.
这种情况下只有 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_;
   }

};

没有,那是绝对没问题 - 我做同样的

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top