T
Tony Johansson
Hello!
I have this wrapper class Integer below that I use when testing operator
overloading.
A book that I read say that the expression
Integer i;
i+5 is translated to operator+(i,5) using the stand-alone helper function.
If Integer's constructor were not declared as explicit, the previous would
have one more possible translation which is
operator+(i, Integer(5))
for which the constructor would first convert the value 5 to the Integer
type, and then two object of type Integer would be added. Therefore the code
would have an ambiguous translation, and the compiler would refuse to
compile it.With the explicit specification, the latter possibility does not
apply, and the code compiles.
Now to my first question.Wwhy would the code have ambiguous translation?
My second question. Why does it works perfactly without this specification
explicit?
My third question in what cases would I get this mentioned about ambiguous
translation?
int main()
{
Integer i(2);
Integer k = i+5;
cout << k.get();
return 0;
}
class Integer
{
public:
Integer (int i = 0 : value_(i)
{}
int get() const
{ return value_; }
Integer operator+(const Integer& i) const
{
Integer local(value_ + i.value_);
return local;
}
friend Integer operator+(int v, const Integer& i)
{
Integer local(v + i.value_);
return local;
}
private:
int value_;
};
Integer operator+(const Integer& i, int v)
{
Integer local(v + i.get());
return local;
}
//Tony
I have this wrapper class Integer below that I use when testing operator
overloading.
A book that I read say that the expression
Integer i;
i+5 is translated to operator+(i,5) using the stand-alone helper function.
If Integer's constructor were not declared as explicit, the previous would
have one more possible translation which is
operator+(i, Integer(5))
for which the constructor would first convert the value 5 to the Integer
type, and then two object of type Integer would be added. Therefore the code
would have an ambiguous translation, and the compiler would refuse to
compile it.With the explicit specification, the latter possibility does not
apply, and the code compiles.
Now to my first question.Wwhy would the code have ambiguous translation?
My second question. Why does it works perfactly without this specification
explicit?
My third question in what cases would I get this mentioned about ambiguous
translation?
int main()
{
Integer i(2);
Integer k = i+5;
cout << k.get();
return 0;
}
class Integer
{
public:
Integer (int i = 0 : value_(i)
{}
int get() const
{ return value_; }
Integer operator+(const Integer& i) const
{
Integer local(value_ + i.value_);
return local;
}
friend Integer operator+(int v, const Integer& i)
{
Integer local(v + i.value_);
return local;
}
private:
int value_;
};
Integer operator+(const Integer& i, int v)
{
Integer local(v + i.get());
return local;
}
//Tony