同时定义运算符void *和运算符bool [英] define both operator void* and operator bool

查看:164
本文介绍了同时定义运算符void *和运算符bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用一​​个operator bool和一个operator void*创建一个类,但是编译器说它们是模棱两可的.有什么方法可以向编译器解释要使用的运算符,还是不能同时使用它们?

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";
    }
} 

推荐答案

您可以直接致电运营商.

You could call the operator directly.

int main()
{
    A a1, a2;
    if (static_cast<bool>(a1) == static_cast<bool>(a2)){
        cout << "hello";
    }
} 

但是,在这种情况下,您似乎应该定义operator==()而不是依赖于转换.

In this case, though, it looks like you should define operator==() and not depend on conversions.

这篇关于同时定义运算符void *和运算符bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆