Overload insertion operator << for cout - C++ Class

C++ examples for Class:Operator Overload

Description

Overload insertion operator << for cout

Demo Code

#include <iostream>
using namespace std;
class Complex//from w w  w  .j  a  v  a 2  s.c o  m
{
   // prototype for the overloaded insertion operator
   friend ostream& operator<<(ostream&, const Complex&);
   private:
   double realPart;
   double imaginaryPart;
   public:
   Complex(double real = 0.0, double imag = 0.0)  // inline constructor
   {
      realPart = real;
      imaginaryPart = imag;
   }
};
// overloaded insertion operator function
ostream& operator<<(ostream& out, const Complex& num)
{
   char sign = '+';                      // set the
   if (num.imaginaryPart < 0) 
      sign = '-';  // correct sign
   if (num.realPart == 0 && num.imaginaryPart == 0)
          cout << 0;
   else if (num.imaginaryPart == 0)
          cout << num.realPart;
   else if (num.realPart == 0)
          cout << num.imaginaryPart << 'i';
   else
          cout << num.realPart << ' ' << sign << ' ' << abs(num.imaginaryPart) << 'i';
   return out;
}
int main()
{
   Complex complexOne(12.5,-18.2);
   cout << "The complex number just created is " << complexOne << endl;
   return 0;
}

Result


Related Tutorials