home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C Programming Starter Kit 2.0
/
SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso
/
tybc4
/
class6.cpp
< prev
next >
Wrap
C/C++ Source or Header
|
1993-04-02
|
1KB
|
81 lines
// Program demonstrates operators and friend operators
#include <iostream.h>
class Complex
{
protected:
double x;
double y;
public:
Complex(double real = 0, double imag = 0)
{ assign(real, imag); }
Complex(Complex& c);
void assign(double real = 0, double imag = 0);
double getReal() const { return x; }
double getImag() const { return y; }
Complex& operator =(Complex& c);
Complex& operator +=(Complex& c);
friend Complex operator +(Complex& c1, Complex& c2);
friend ostream& operator <<(ostream& os, Complex& c);
};
Complex::Complex(Complex& c)
{
x = c.x;
y = c.y;
}
void Complex::assign(double real, double imag)
{
x = real;
y = imag;
}
Complex& Complex::operator =(Complex& c)
{
x = c.x;
y = c.y;
return *this;
}
Complex& Complex::operator +=(Complex& c)
{
x += c.x;
y += c.y;
return *this;
}
Complex operator +(Complex& c1, Complex& c2)
{
Complex result(c1);
result.x += c2.x;
result.y += c2.y;
return result;
}
ostream& operator <<(ostream& os, Complex& c)
{
os << "(" << c.x << " + i" << c.y << ")";
return os;
}
main()
{
Complex c1(3, 5);
Complex c2(7, 5);
Complex c3;
Complex c4(2, 3);
c3 = c1 + c2;
cout << c1 << " + " << c2 << " = " << c3 << "\n";
cout << c3 << " + " << c4 << " = ";
c3 += c4;
cout << c3 << "\n";
return 0;
}