Reputation: 10936
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?
Upvotes: 0
Views: 208
Reputation: 42899
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_; }
Upvotes: 2
Reputation: 527
You need an operator == like that:
bool operator==(const Foo& f) { return x_==f.x_; }
Upvotes: 0
Reputation: 71969
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.
Upvotes: 0
Reputation: 5209
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
.
Upvotes: 0