In the program below I am trying to overload the +, -, *, >>, <<, ==, and != operators. I cannot get the code to compile and am not sure what I'm doing wrong. I have posted the code and error messages below:
Complex.h
#include <iostream>
using namespace std;
class Complex
{
public:
Complex();
Complex(double, double);
Complex operator+(Complex);
Complex operator-(Complex);
Complex operator*(Complex);
bool operator==(Complex);
bool operator!=(Complex);
friend ostream &operator<<(ostream &, Complex &);
friend istream &operator>>(istream &, Complex &);
private:
double real;
double imaginary;
};
Complex.cpp
#include <iostream>
#include "Complex.h"
using namespace std;
Complex::Complex()
{
}
Complex::Complex( double a, double b )
{
real = a;
imaginary = b;
}
// addition operator
Complex Complex::operator+(Complex operand2)
{
return Complex( real + operand2.real,
imaginary + operand2.imaginary);
} // end function operator+
// subtraction operator
Complex Complex::operator-( Complex operand2 )
{
return Complex( real - operand2.real,
imaginary - operand2.imaginary);
} // end function operator-
// mutilplication operator
Complex Complex::operator*( Complex operand2 )
{
return Complex( real * operand2.real,
imaginary * operand2.imaginary);
} // end function operator-
bool Complex::operator==( Complex operand2 )
{
bool result = true;
double first = real;
double second = imaginary;
if(real == imaginary)
{
result = true;
}
else
result = false;
return result;
}
bool Complex::operator!=( Complex operand2 )
{
bool result = true;
double first = real;
double second = imaginary;
if(real != imaginary)
{
result = true;
}
else
result = false;
return result;
}
ostream &operator<<(ostream &out, Complex &c)
{
out << c.real << c.imaginary;
return out;
}
istream &operator>>(istream &in, Complex &c)
{
in >> c.real;
in.ignore();
in >> c.imaginary;
return in;
}
Main.cpp
#include <iostream>
using std::cout;
using std::endl;
#include "Complex.h"
int main()
{
Complex x, y, z;
// Test creation of Complex objects
cout << "x: ";
cout << x;; // REPLACE all print() calls with output (<<) statements
cout << "\ny: ";
cout << y;
cout << "\nz: ";
cout << z;
cout << endl;
// Test overloaded addition operator
x = y + z;
cout << y << "+" << z << " = " << x << endl;
// Test overloaded subtraction operator
x = y - z;
cout << y << " - " << z << " = " << x << endl;
// ADD code to test overloaded multiplication operator
x = y * z;
cout << y << " * " << z << " = " << x << endl;
// ADD code to test equality (==) operator
cout << y << ( ( y == z ) ? " == " : " != " ) << z
<< " according to the overloaded == operator\n";
// ADD code to test inequality (!=) operator
cout << y << ( ( y != z ) ? " == " : " != " ) << z
<< " according to the overloaded == operator\n";
system("pause");
return 0;
}
Error messages:
'Complex' : 'class' type redefinition
see declaration of 'Complex'
'x' uses undefined class 'Complex'
'y' uses undefined class 'Complex'
'z' uses undefined class 'Complex'