C/C++ Programming Pearls

  An example working with classes using operators.

mycomplex.h
class mycomplex {
    double re, im;
  public:
     mycomplex(double r, double i) {
	re = i;
	im = i;
    } mycomplex(double r) {
	re = r;
	im = 0;
    }
    mycomplex() {
	re = im = 0;
    }

    friend mycomplex operator + (mycomplex, mycomplex);
    friend mycomplex operator - (mycomplex, mycomplex);
    friend mycomplex operator - (mycomplex);
    friend mycomplex operator *(mycomplex, mycomplex);
    friend mycomplex operator / (mycomplex, mycomplex);

    friend bool operator == (mycomplex, mycomplex);
    friend bool operator != (mycomplex, mycomplex);

    double real();
    double imag();
};

  The class functions are defined in mycomplex.cc.

mycomplex.cc
#include "mycomplex.h"
mycomplex operator + (mycomplex a1, mycomplex a2)
{
  return mycomplex (a1.re + a2.re, a1.im + a2.im);
}

mycomplex operator - (mycomplex a1, mycomplex a2)
{
  return mycomplex (a1.re - a2.re, a1.im - a2.im);
}

mycomplex operator - (mycomplex a1)
{
  return mycomplex (-a1.re, -a1.im);
}
mycomplex operator *(mycomplex a1, mycomplex a2)
{
  return mycomplex (a1.re * a2.re + a1.im * a2.im,
		    a1.re * a2.im + a1.im * a2.re);
}



double mycomplex::real ()
{
     return mycomplex::re;
 }

double mycomplex::imag ()
{
     return mycomplex::im;
}


bool operator == (mycomplex a1, mycomplex a2) {
  if (a1.re == a2.re && a1.im == a2.im)
  {
     return true;
  }
     else
  {
     return false;
  }

  }

maincomplex.cc
#include <iostream>
#include "mycomplex.h"
using namespace std;
int main()
{
    mycomplex a=2.3;
    mycomplex b=mycomplex(1,4);
    mycomplex c=a*b;
    mycomplex d=mycomplex(1,4);
    cout << c.real() << endl;
    if (a == d)
      {
      cout << "yes equal" << endl;
      }

    
}

SourceForge.net Logo