Overloading + with a member function...
Jun 24, 2014 at 5:16pm UTC
So, take the following;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
template <typename type, typename type2>
double add(type x,type2 y)
{
return x+y;
}
class TrivialInt
{
public :
int m_value;
TrivialInt(int input = 0):m_value(input)
{
//
}
double operator +(double inValue)
{
return inValue+m_value;
}
};
int main()
{
TrivialInt instance(3);
cout<<add(instance,2.3);
return 0;
}
This prints the expected '5.3'.
But, if I reverse
add(instance,2.3)
to
add(2.3,instance)
, then I get an error, because it doesn't know what to do with int+TrivialInt only the other way around. (TrivialInt+int)
I could fix this with friend functions (programming for both contingencies);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
template <typename type, typename type2>
double add(type x,type2 y)
{
return x+y;
}
class TrivialInt
{
public :
int m_value;
TrivialInt(int input = 0):m_value(input)
{
//
}
friend double operator +(double inValue,TrivialInt& inTrivial);
friend double operator +(TrivialInt& inTrivial,double inValue);
};
double operator +(double inValue,TrivialInt& inTrivial)
{
return inTrivial.m_value + inValue;
}
double operator +(TrivialInt& inTrivial,double inValue)
{
return inTrivial.m_value + inValue;
}
int main()
{
TrivialInt instance(3);
cout<<add(2.3,instance)<<"\n" ;
cout<<add(instance,2.3);
return 0;
}
So my question is really 'can I do this with a member function'?
Last edited on Jun 24, 2014 at 5:24pm UTC
Jun 24, 2014 at 11:17pm UTC
The short answer is no.
To call a member of a class, you need an object of that class. When dealing with binary operators the object of the class is always the left hand operand.
ie
1 2
TrivialInt instance(3);
instance + 2.3;
2.3 + instance
// this is illegal
Last edited on Jun 24, 2014 at 11:17pm UTC
Jun 25, 2014 at 4:50am UTC
Thanks!
Topic archived. No new replies allowed.