问题
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. 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. But the compiler gives the following error.
error: call of overloaded `dummy(sample&)' is ambiguous
note: candidates are: dummy::dummy(const dummy&)
note: 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?
回答1:
The line:
d = (dummy)ob1
attempts to do the following:
- Construct a
dummy
object fromobj1
- Assign that temporary
dummy
object tod
Part 1 is what causes the problems. 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. It finds that there are two ways to do this:
- Call
operator int
- Call
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);
}
来源:https://stackoverflow.com/questions/9476792/ambiguity-while-overloading-the-cast-operator