Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

DZone's Guide to

# OprOvrcmplx.cpp

·
Free Resource

Comment (0)

Save
{{ articles[0].views | formatCount}} Views
```#include

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;

}

```
Topics:

Comment (0)

Save
{{ articles[0].views | formatCount}} Views

Opinions expressed by DZone contributors are their own.