Page 156 - DCAP404 _Object Oriented Programming
P. 156
Unit 7: Operator Overloading
Overloading the binary addition (+) operator Notes
Let’s take a look at an example of a binary operator overloaded both ways. First, overloading
operator+ using the friend function:
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
// Overload cCents + int
friend Cents operator+(Cents &cCents, int nCents);
int GetCents() { return m_nCents; }
};
// note: this function is not a member function!
Cents operator+(Cents &cCents, intnCents)
{
return Cents(cCents.m_nCents + nCents);
}
Now, the same operator overloaded using the member function method:
class Cents
{
private:
int m_nCents;
public:
Cents(int nCents) { m_nCents = nCents; }
// Overload cCents + int
Cents operator+(int nCents);
int GetCents() { return m_nCents; }
};
// note: this function is a member function!
Cents Cents::operator+(int nCents)
{
return Cents(m_nCents + nCents);
}
Our two-parameter friend function becomes a one-parameter member function, because the
leftmost parameter (cCents) becomes the implicit *this parameter in the member function version.
LOVELY PROFESSIONAL UNIVERSITY 149