DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

OprOvrcmplx.cpp

02.01.2008
| 961 views |
  • submit to reddit
        
#include <iostream>

using namespace std;


class complex
{
public:
        complex () {};
        complex (float, float);
	complex operator+(complex c);
	complex operator-(complex c);
	complex operator*(complex c);
	complex operator/(complex c);
        friend ostream& operator<<(ostream& os, complex x);
private:
	float real,imag;
};

complex::complex(float real, float imag)
{
 (*this).real = real;
 (*this).imag = imag;
}

complex complex::operator+(complex c)
{
	complex sum;
	sum.real = real + c.real;
	sum.imag = imag + c.imag;

	return sum;
}

complex complex::operator-(complex c)
{
	complex diff;
	diff.real = real - c.real;
	diff.imag = imag - c.imag;

	return diff;
}

complex complex::operator*(complex c)
{
	complex prod;

	prod.real = real*c.real - imag*c.imag;
	prod.imag = imag*c.real + real*c.imag;

	return prod;
}

complex complex::operator/(complex c)
{
	complex quot;

	quot.real = real*c.real + imag*c.imag;
	quot.imag = imag*c.real - real*c.imag;

	quot.real /= (c.real*c.real+c.imag*c.imag);
	quot.imag /= (c.real*c.real+c.imag*c.imag);

	return quot;
}

ostream& operator<<(ostream& os, complex x)
{
 if (x.imag < 0.0)
   os << x.real << " - i" << abs(x.imag) << endl;
 else
   os << x.real << " + i" << x.imag << endl;
 return os;
}




void main (void)

{

        complex a(1,2);
        complex b(3,4);

        cout << "  a = " << a << endl;
        cout << "  b = " << b << endl;
        cout << "a+b = " << a+b << endl;
        cout << "a-b = " << a-b << endl;
        cout << "a*b = " << a*b << endl;
        cout << "a/b = " << a/b << endl;

}