class Int {
int i;
public:
Int(int i = 0);
friend Int operator + (Int, Int);
operatorint () const;
int iVal();
};
Int::Int (int a) : i(a)
{
}
Int operator + (Int a, Int b)
{
return a.i + b.i;
}
Int::operatorint () const
{
return i;
}
int Int::iVal()
{
return i;
}
int main(int argc, constchar * argv[])
{
Int a = 7;
int c = 2;
Int h = a + (Int)c;
return 0;
}
Why does the sum work only with the casting?
In fact if I write
Int h = a + c;
I get this error: "Use of overloaded operator '+' is ambiguous (with operand types 'Int' and 'int')".
Because an Int can be converted to int and an int can be converted to an Int, the compiler cannot know whether it is supposed to use operator+(Int,Int) or operator+(int,int).
This is why you should avoid conversion constructors (make them explicit) and conversion operators (those can be explicit only in C++11).