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)。我觉得这很整洁