Def*_*ult 5 c++ operators ambiguity
我尝试用一个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";
}
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是你要定义operator bool的是你想要的声音operator ==.或者,您可以显式转换为void *:
if ((void *)a1 == (void *)a2) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
......但这真的很奇怪.不要那样做.相反,operator ==在里面定义你喜欢这个class A:
bool operator==(const A& other) const {
return /* whatever */;
}
Run Code Online (Sandbox Code Playgroud)
您可以直接致电接线员。
int main()
{
A a1, a2;
if (static_cast<bool>(a1) == static_cast<bool>(a2)){
cout << "hello";
}
}
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,您似乎应该定义operator==()而不是依赖于转换。
| 归档时间: |
|
| 查看次数: |
1899 次 |
| 最近记录: |