[英]Ambiguity while overloading the cast operator
Consider the sample code below: 考虑下面的示例代码:
#include <iostream>
using namespace std;
class dummy
{
private:
int y;
public:
dummy(int b = 0) : y(b) {
}
friend ostream& operator<<(ostream& os, const dummy& obj);
};
ostream& operator<<(ostream& os, const dummy& obj)
{
os << obj.y;
return os;
}
class sample
{
private:
int x;
public:
sample(int a = 0) : x(a)
{
}
operator dummy()
{
dummy d(100);
return d;
}
operator int()
{
return x;
}
};
int main()
{
sample ob1(5);
dummy d;
//d = ob1; //Line1
d = (dummy)ob1; //Line2
cout << d << "\n";
}
In Line1, an implicit cast is done. 在Line1中,完成了隐式转换。 I understand how the implicit casting works in this case.
我了解在这种情况下隐式强制转换的工作方式。 The compiler gives no errors.
编译器没有错误。
But in Line2, an explicit cast of sample
object is done to dummy
object. 但是在Line2中,对
dummy
对象进行了显式的sample
对象转换。 But the compiler gives the following error. 但是编译器给出以下错误。
error: call of overloaded `dummy(sample&)' is ambiguous
错误:重载的“ dummy(sample&)”调用不明确
note: candidates are: dummy::dummy(const dummy&)
注意:候选者是:dummy :: dummy(const dummy&)
note: dummy::dummy(int)
注意:dummy :: dummy(int)
Questions: 问题:
Why is these errors occurring? 为什么会发生这些错误?
I do not understand the meaning of the error messages. 我不理解错误消息的含义。 Why the candidate functions of
dummy
class mentioned in the errors? 为什么在错误中提到
dummy
类的候选函数?
The line: 该行:
d = (dummy)ob1
attempts to do the following: 尝试执行以下操作:
dummy
object from obj1
obj1
构造一个dummy
对象 dummy
object to d
dummy
对象分配给d
Part 1 is what causes the problems. 第1部分是导致问题的原因。 To construct the temporary
dummy
object the compiler must search for some way to convert obj1
into a type which a dummy
can be constructed from. 为了构建临时
dummy
对象,编译器必须寻找一些方法来转换obj1
到其中的一个类型的dummy
可以从构成。 It finds that there are two ways to do this: 它发现有两种方法可以做到这一点:
operator int
operator int
operator dummy
operator dummy
You do not tell it which one of these two alternatives you want it to take, and so the code is ambiguous. 您没有告诉它要采用这两种选择中的哪一种,因此代码是不明确的。
Your problem could be recreated (with the extraneous parts removed) as follows: 您的问题可以按照以下步骤重新创建(除去多余的部分):
struct t_1 {};
struct t_2 {};
struct sample {
operator t_1() const{ return t_1(); }
operator t_2() const{ return t_2(); }
};
void f(t_1) {}
void f(t_2) {}
int main() {
sample obj1;
//overload resolution will fail
//disambiguate with f(obj1.operator t_1()) or f(obj1.operator t_2())
f(obj1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.