Complex numbers

The following code is the class header describing a complex number class.
/* 
** Name:     complex.h
** Author:   Leo Liberti
** Purpose:  header file for a complex numbers class
** Source:   GNU C++
** History:  061019 work started
*/

#ifndef _COMPLEXH
#define _COMPLEXH

#include<string>
#include<iostream>

class Complex {

 public:

  Complex();
  Complex(double re, double im);
  ~Complex();

  double getReal(void);
  double getImaginary(void);
  void setReal(double re);
  void setImaginary(double im);
  void fromString(const std::string& complexString);

  Complex operator+(Complex& theComplex);
  Complex operator-(Complex& theComplex);
  Complex operator*(Complex& theComplex);
  Complex operator/(Complex& theComplex);

 private:
  double real;
  double imag;
};

std::ostream& operator<<(std::ostream& out, Complex& theComplex);

#endif
Write the corresponding implementation file complex.cxx. Test it on the following main() function definition, using the command \fbox{\tt ./test 2.1+0.2i / 0.2-0.3i} . The output should be \fbox{\tt
2.76923 + 5.15385i} .
/* 
** Name:     test.cxx
** Author:   Leo Liberti
** Purpose:  testing the complex numbers class
** Source:   GNU C++
** History:  061019 work started
*/

#include <iostream>
#include <string>
#include "complex.h"

int main(int argc, char** argv) {
  using namespace std;
  if (argc < 4) {
    cerr << "need an operation on command line" << endl;
    cerr << "   e.g. ./test 4.3+3i - 2+3.1i" << endl;
    cerr << "   (no spaces within each complex number, use spaces to\n";
    cerr << "    separate the operands and the operator - use arithmetic\n";
    cerr << "    operators only)" << endl;
    return 1;
  }
  string complexString1 = argv[1];
  string complexString2 = argv[3];
  Complex complex1;
  complex1.fromString(complexString1);

  Complex complex2;
  complex2.fromString(complexString2);

  Complex complex3;
  if (argv[2][0] == '+') {
    complex3 = complex1 + complex2;
  } else if (argv[2][0] == '-') {
    complex3 = complex1 - complex2;
  } else if (argv[2][0] == '*' || argv[2][0] == '.') {
    argv[2][0] = '*';
    complex3 = complex1 * complex2;
  } else if (argv[2][0] == '/') {
    complex3 = complex1 / complex2;
  }
  cout << complex1 << " " << argv[2][0] << " (" << complex2 << ") = "
       << complex3 << endl;
  return 0;
}
Use the following Makefile to compile (use tabs, not spaces after each label -- for that you need to use the Emacs editor):
# Name:     complex.Makefile
# Author:   Leo Liberti
# Purpose:  makefile for complex class project
# Source:   GNU C++
# History:  061019 work started

CXXFLAGS = -g

all: test

test: complex.o test.cxx
        c++ $(CXXFLAGS) -o test test.cxx complex.o

complex.o: complex.cxx complex.h
        c++ $(CXXFLAGS) -c -o complex.o complex.cxx

clean:
        rm -f *~ complex.o test



Subsections

Leo Liberti 2008-01-12