Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 又快又脏的操作员=_C++_Operator Overloading - Fatal编程技术网

C++ 又快又脏的操作员=

C++ 又快又脏的操作员=,c++,operator-overloading,C++,Operator Overloading,在我的课堂上,我经常写一个快速的操作符=通过返回!(*此==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!=(cons

在我的课堂上,我经常写一个快速的
操作符=通过返回
!(*此==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);
    }
};

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

不,这绝对没问题-我做的完全一样。

我相信这是实现
操作符的首选方法=这样您就不会重复自己的操作,并且您保证与
操作符==
定义
操作符有正确的关系=作为
!运算符==
很好

为了使这些简单的等价运算符易于定义,我总是使用。
只有
运算符==
运算符的情况=(即使用)不会获得太多收益

但是,当您需要小于或大于,或者是
操作符+
操作符*
等的组合时,这就变得非常方便了

你的例子如下

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

};
class-Foo:private-boost::equality\u compariable
{
私人:
int n_;
std::string str;
公众:
...
布尔运算符==(常量Foo和rhs)常量
{
返回n_==rhs.n_=&str_==rhs.str;
}
};

+1表示仍然喜欢运算符重载且不相等(ObjA、ObjB)。我觉得这很整洁