Operators as friends

Except for the operators =, (), [], and ->, operators may be defined as friend functions rather than as members of a class. This is suitable for operators that do not modify their operands.

#include<iostream.h>
class Complex {
   int v1, v2;
public:
   friend Complex * operator+(Complex, Complex);
   void printout();
   Complex(int iv1, int iv2);
};

Complex * operator+(Complex L, Complex R) 
{
   return new Complex(L.v1+R.v1, L.v2+R.v2); 
}

Complex::Complex(int iv1, int iv2) 
{ 
   v1=iv1; 
   v2=iv2; 
}

void Complex::printout() 
{ 
   cout<printout();
   return 0;
}
Simple text version to compile and run.


Next note in series

Back to index