Equality check for objects of classes with explicit constructor only

Why can I not check two objects of classes with explicit constructor only for equality? The following code does not compile

struct Foo
{
    explicit Foo(int x) : x_(x) {}
    int x_;
};

int main()
{
    Foo(1) == Foo(1);
}

Do I have to declare operator == explicitly?


You need to overload the equality operator== :

struct Foo {
    explicit Foo(int x) : x_(x) {}
    int x_;
};

bool operator==(Foo const &lhs, Foo const& rhs) { return lhs.x_ == rhs.x_; }

LIVE DEMO


How shoud compiler know how it should compare them? Either define operator== or use Foo(1).x_ == Foo(1).x_ if you want to compare those ints.

Maybe you misunderstood what explicit constructor means. It's about asignment operator = and not comparism. Marking your constructor explicits disables following snippet to compile: Foo f = 1 .


Yes, the compiler does not generate equality for you, so you have to do it yourself. This isn't about explicit constructors either; at no point has C++ ever allowed comparing classes or structs implicitly.

链接地址: http://www.djcxy.com/p/73786.html

上一篇: 我班的等号运算符(==)不起作用

下一篇: 只有具有显式构造函数的类的对象的平等检查