Is there something like Java equals()
? To compare if object is the same type ?
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof ViewMode)) {
return false;
}
ViewMode dm = (ViewMode) obj;
return dm.width == w
&& dm.h == h
&& dm.b == b
&& dm.f == f;
}
public int hashCode() {
return w ^ h ^ f ^ b ;
}
For the idiomatic equivalent of your example, you would define operator==
as follows:
friend bool operator==(const ViewMode &lhs, const ViewMode &rhs) {
return (lhs.w == rhs.w) && the rest;
}
friend bool operator!=(const ViewMode &lhs, const ViewMode &rhs) {
return !(lhs == rhs);
}
In C++ you don't normally write a function to allow ViewMode
objects to be compared with something that has nothing at all to do with ViewMode
. I suppose that if you really wanted that comparison to return false, rather than refusing to compile, then you could add a couple of template operators (as free functions, outside the class):
template <typename T>
bool operator==(const ViewMode &, const T&) {
return false;
}
template <typename T>
bool operator==(const T &, const ViewMode&) {
return false;
}
but I really don't recommend it. That Java idiom doesn't apply to C++, because in C++ you pretty much should never have an object, but have no idea of its type.
If you want your equals function to be virtual, then it's probably best to write an equals()
virtual function, rather than using operator==
for it. You'd write it to take a const ViewObject &
as parameter, so no need for any equivalent to the instanceof
check. Which is just as well, because C++ does not have any way to take an object of totally unknown type and test whether it is an instance of a specified type.
You rarely need a polymorphic equals function in C++, but if you were using it for example in std::unordered_map
, then you'd specify the extra template parameters to the unordered_map
. Give it an equality comparison function that takes two pointers and calls equals
on one or the other, and a hash function that does something sensible.
You might be able to use the typeid
operator for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With