Overloading Arithmetic operators in c++

Some of the most commonly used operators in C++ are the arithmetic operators — that is, the plus operator (+), minus operator (-), multiplication operator (*), and division operator (/). Note that all of the arithmetic operators are binary operators — meaning they take two operands — one on each side of the operator. All four of these operators are overloaded in the exact same way.

Overloading operators using friend functions

When the operator does not modify its operands, the best way to overload the operator is via friend function [If the operators (such as increment, decrement and dereference) modify the operands then they should be members of the class].  None of the arithmetic operators modify their operands (they just produce and return a result), so we will utilize the friend function overloaded operator method here.

class Cents
{
  private:
          int m_nCents;
  public:
          Cents(int nCents) { m_nCents = nCents; }
          // Add Cents + Cents
          friend Cents operator+(const Cents &c1, const Cents &c2);
          int GetCents() { return m_nCents; }
};
 
    // note: this function is not a member function!
    Cents operator+(const Cents &c1, const Cents &c2)
    {
      // use the Cents constructor and operator+(int, int)
         return Cents(c1.m_nCents + c2.m_nCents);
    }

    int main()
    {
        Cents cCents1(6);
        Cents cCents2(8);
        Cents cCentsSum = cCents1 + cCents2;
        std::cout << "I have " << cCentsSum .GetCents() << " cents." << std::endl;

        return 0;
    }

Output:
I have 14 cents.
 
Source:
LearnCPP.com

0 comments:

Post a Comment