Use a member function to overload the unary -. : Unary Operator « Overload « C++






Use a member function to overload the unary -.

  
#include <iostream>

using namespace std;

class three_d {
  int x, y, z;
public:
  three_d() { x = y = z = 0; }
  three_d(int i, int j, int k) { x = i; y = j; z = k; }

  three_d operator+(three_d rh_op);

  three_d operator+(int rh_op);

  three_d operator-(three_d rh_op);

  three_d operator=(three_d rh_op);

  bool operator==(three_d rh_op);

  three_d operator-();

  friend ostream &operator<<(ostream &strm, three_d op);

  friend three_d operator+(int lh_op, three_d rh_op);
};

three_d three_d::operator+(three_d rh_op)
{
  three_d temp;

  temp.x = x + rh_op.x;
  temp.y = y + rh_op.y;
  temp.z = z + rh_op.z;

  return temp;
}

three_d three_d::operator+(int rh_op)
{
  three_d temp;

  temp.x = x + rh_op;
  temp.y = y + rh_op;
  temp.z = z + rh_op;

  return temp;
}

three_d three_d::operator-(three_d rh_op)
{
  three_d temp;

  temp.x = x - rh_op.x;
  temp.y = y - rh_op.y;
  temp.z = z - rh_op.z;

  return temp;
}

three_d three_d::operator-()
{
  three_d temp;

  temp.x = -x;
  temp.y = -y;
  temp.z = -z;
  return temp;
}

three_d three_d::operator=(three_d rh_op)
{
  x = rh_op.x;
  y = rh_op.y;
  z = rh_op.z;

  return *this;
}

bool three_d::operator==(three_d rh_op)
{
  if( (x == rh_op.x) && (y == rh_op.y) && (z == rh_op.z) )
    return true;

  return false;
}

ostream &operator<<(ostream &strm, three_d op) {
  strm << op.x << ", " << op.y << ", " << op.z << endl;

  return strm;
}

three_d operator+(int lh_op, three_d rh_op) {
  three_d temp;

  temp.x = lh_op + rh_op.x;
  temp.y = lh_op + rh_op.y;
  temp.z = lh_op + rh_op.z;

  return temp;
}

int main()
{
  three_d objA(1, 2, 3), objB(10, 10, 10), objC;

  cout << "This is objA: " << objA;
  cout << "This is objB: " << objB;

  objC = -objA;
  cout << "This is -objA: " << objC;

  objC = objA + objB;
  cout << "objA + objB: " << objC;

  objC = objA - objB;
  cout << "objA - objB: " << objC;

  objC = objA + 10;
  cout << "objA + 10: " << objC;

  objC = 100 + objA;
  cout << "100 + objA: " << objC;

  if(objA == objB) 
     cout << "objA is equal to objB.\n";
  else 
     cout << "objA is not equal to objB.\n";

  return 0;
}
  
    
  








Related examples in the same category

1.Overload a unary operator.Overload a unary operator.