快速而肮脏的操作员!=

Rob*_*Rob 7 c++ operator-overloading

在我的课程中,我经常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);
    }
};
Run Code Online (Sandbox Code Playgroud)

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

bdu*_*kes 11

我相信这是首选的实施方法,operator!=这样你就不会重复自己,并保证你有正确的关系operator==.