开发者

define both operator void* and operator bool

I tried creating a class with one operator bool and one operator vo开发者_JAVA技巧id*, 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜