#include <stdio.h>
#include <stdlib.h>
#include <iostream.h>

class complex {
private:  // private data
  // the private real and imaginary components of the complex
  float p_real, p_imaginary;

  // the string (char *) representation of the complex, updated by print()
  char *p_string;
public:
  // Three different constructors:
  //    a constructor which takes no arguments; initializes complex to 0
  complex() { p_string = NULL; p_real = 0.0; p_imaginary = 0.0; }

  //    a constructor which takes one argument: sets the real part, and
  //    makes the imaginary part 0
  complex(float r) { p_string = NULL; p_real = r; p_imaginary = 0.0; }

  //    a constructor which takes two arguments: real and imaginary parts
  complex(float r, float i) { p_string = NULL; p_real = r, p_imaginary = i; }

  // destructor: deallocate memory for p_string if it was allocated
  ~complex() { if (p_string != NULL) delete p_string; }

  // member functions
  float real(void) { return p_real; }		// accessor function
  float imaginary(void) { return p_imaginary; } // accessor function
  char *print(void);

  // overloaded operators
  complex operator+(complex b);
  complex operator-(complex b);
  int operator==(complex b);
};


complex complex::operator+(complex b)
{
  float real, imaginary;

  real = p_real + b.p_real;
  imaginary = p_imaginary + b.p_imaginary;

  return complex(real, imaginary);
}

complex complex::operator-(complex b)
{
  return complex(p_real - b.p_real, p_imaginary - b.p_imaginary);
}

int complex::operator==(complex b)
{
  // if any of the members don't match, return 0
  if (p_real != b.p_real)
    return 0;
  if (p_imaginary != b.p_imaginary)
    return 0;

  // everything ok: return 1
  return 1;
}

// Note, this is an example of where using C++ streams (<< and >>)
// would be really nice, but we'll save that for a later example.
char *complex::print(void)
{
  if (p_string == NULL)
    p_string = new char[30];

  sprintf(p_string, "%.2f%+.2fi", p_real, p_imaginary);
  return p_string;
}

// main
int main(int argc, char *argv[])
{
  complex a(1.4, 4.2);
  complex b(2.3, 4.0);
  complex c;

  c = b - a;
  
  // 2.30+4.00i minus 1.40+4.20i is 0.90-0.20i
  printf("%s minus %s is %s\n", b.print(), a.print(), c.print());

  if (a == b)
    printf("a is equal to b\n");   // no output

  if (a == b-c)
    printf("a = b-c!\n");   // a = b-c!

}

