问题
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";
}
}
回答1:
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.
回答2:
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 */;
}
来源:https://stackoverflow.com/questions/4294873/define-both-operator-void-and-operator-bool