//Complex.h
#ifndef COMPLEX_H
#define COMPLEX_H
#include<iostream>
class Complex
{
private:
double x;
double y;
public:
Complex();
Complex(double a, double b = 0.0);
Complex operator+(const Complex& c)const;
Complex operator-(const Complex& c)const;
Complex operator*(const Complex& c)const;
Complex operator*(double n) const;
Complex operator~();
friend Complex operator*(double n, const Complex& c);
friend std::istream& operator>>(std::istream& is, Complex& c);
friend std::ostream& operator<<(std::ostream& os, const Complex& c);
};
#endif // !COMPLEX_H
//Complex.cpp
#include "Complex.h"
//constructor
Complex::Complex()
{
x = 0.0;
y = 0.0;
}
Complex::Complex(double a, double b)
{
x = a;
y = b;
}
//operator overloading
Complex Complex::operator+(const Complex& c) const
{
Complex sum;
sum.x = x + c.x;
sum.y = y + c.y;
return sum;
}
Complex Complex::operator-(const Complex& c) const
{
Complex diff;
diff.x = x - c.x;
diff.y = y - c.y;
return diff;
}
Complex Complex::operator*(const Complex& c) const
{
Complex mult;
mult.x = x * c.x - y * c.y;
mult.y = x * c.y + y * c.x;
return mult;
}
Complex Complex::operator*(double n) const
{
Complex mult;
mult.x = x * n;
mult.y = y * n;
return mult;
}
Complex Complex::operator~()
{
return Complex(x, -y);
}
//friend method:
Complex operator*(double n, const Complex& c)
{
return c * n;
}
std::istream& operator>>(std::istream& is, Complex& c)
{
std::cout << "real: ";
is >> c.x;
std::cout << "imaginary: ";
is >> c.y;
return is;
}
std::ostream& operator<<(std::ostream& os, const Complex& c)
{
os << "(" << c.x << "," << c.y << "i)\n";
return os;
}
//usecomp.cpp
#include<iostream>
#include"Complex.h"
using namespace std;
int main()
{
Complex a(3.0, 4.0);
Complex c;
cout << "Enter a complex number (q to quit):\n";
while (cin >> c)
{
cout << "c is " << c << "\n";
cout << "complex conjugate is " << ~c << "\n";
cout << "a is " << a << "\n";
cout << "a + c is " << a + c << "\n";
cout << "a - c is " << a - c << "\n";
cout << "a * c is " << a * c << "\n";
cout << "2 * c is " << 2 * c << "\n";
cout << "Enter a complex number (q to quit):\n";
}
cout << "Done!\n";
return 0;
}