operator Overloading in C++ Example Question for Quiz and solution


1.  Overload the ‘+’ and ‘-’ operator in this class that by using these operators one should be able to add and subtract the three integers using two objects of this class?

class Nums
{
private:
            int x,y,z;
public:
            Nums (int,int,int);
            Nums ();
            Nums operator+ (const Nums& n1, const Nums& n2);
            Nums operator-(const Nums& n1, const Nums& n2);
                                               
};

Solution:

Nums operator +(const Nums& n1, const Nums& n2)  //Addition
{
          Nums res;
          res.x = n1.x + n2.x;
          res.y = n1.y + n2.y;
          res.z = n1.z + n2.z;
          return res;
}

Nums operator -(const Nums& n1, const Nums& n2) //Subtraction
{
          Nums res;
          res.x = n1.x - n2.x;
          res.y = n1.y - n2.y;
          res.z = n1.z - n2.z;
          return res;
}