It happens in the first line because the only operator+
available is operator+(Int&)
(which has an implicit first parameter of Int
for the this
instance). The second line fails because the first parameter is an int
and it has no clue that it needs to convert it before attempting the operation (it doesn't know it needs to use Int::operator+
).
You can avoid that problem by making the operator a non-member friend function (http://ideone.com/YCf7wX)
struct Int
{
int _i;
Int(int i=0) :_i{i} {}
friend Int operator+(const Int& lhs, const Int& rhs);
};
Int operator+(const Int& lhs, const Int& rhs)
{
return lhs._i+rhs._i;
}
int main()
{
Int i;
i + 5;
5 + i;
return 0;
}