define both operator void* and operator bool

﹥>﹥吖頭↗ 提交于 2019-12-13 13:06:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!