定义运算符 void* 和运算符 bool
我尝试用一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里的问题是,您正在定义
operator bool
,但从它的声音来看,您想要的是operator ==
。或者,您可以像这样显式转换为void *
:...但这确实很奇怪。不要那样做。相反,在
class A
中定义您的operator ==
:The problem here is that you're defining
operator bool
but from the sounds of it what you want isoperator ==
. Alternatively, you can explicitly cast tovoid *
like this:... but that's really bizarre. Don't do that. Instead, define your
operator ==
like this insideclass A
:您可以直接致电接线员。
但在这种情况下,您似乎应该定义
operator==()
而不是依赖于转换。You could call the operator directly.
In this case, though, it looks like you should define
operator==()
and not depend on conversions.