I tried creating a class with one operator bool
and one operator void*
, but the compiler says they are ambigous. Is there some way I can explain to the compiler what operator to use or can I not have them both?
class A {
public:
operator void*(){
cout << "operator void* is called" << endl;
return 0;
}
operator bool(){
cout << "operator bool is called" << endl;
return true;
}
};
int main()
{
A a1, a2;
if (a1 == a2){
cout << "hello";
}
}
The problem here is that you're defining operator bool
but from the sounds of it what you want is operator ==
. Alternatively, you can explicitly cast to void *
like this:
if ((void *)a1 == (void *)a2) {
// ...
}
... but that's really bizarre. Don't do that. Instead, define your operator ==
like this inside class A
:
bool operator==(const A& other) const {
return /* whatever */;
}
You could call the operator directly.
int main()
{
A a1, a2;
if (static_cast<bool>(a1) == static_cast<bool>(a2)){
cout << "hello";
}
}
In this case, though, it looks like you should define operator==()
and not depend on conversions.
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