定义运算符 void* 和运算符 bool

发布于 2024-10-04 23:23:41 字数 484 浏览 5 评论 0原文

我尝试用一​​个 operator bool 和一个 operator void* 创建一个类,但编译器说它们不明确。有什么方法可以向编译器解释要使用什么运算符,或者我可以不同时使用它们吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦情居士 2024-10-11 23:23:41

这里的问题是,您正在定义 operator bool,但从它的声音来看,您想要的是 operator ==。或者,您可以像这样显式转换为 void *

if ((void *)a1 == (void *)a2) {
    // ...
}

...但这确实很奇怪。不要那样做。相反,在class A中定义您的operator ==

bool operator==(const A& other) const {
    return /* whatever */;
}

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 */;
}
金橙橙 2024-10-11 23:23:41

您可以直接致电接线员。

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文