home *** CD-ROM | disk | FTP | other *** search
- // Program demonstrates friend functions
-
- #include <iostream.h>
-
- class Complex
- {
- protected:
- double x;
- double y;
-
- public:
- Complex(double real = 0, double imag = 0);
- Complex(Complex& c) { assign(c); }
- void assign(Complex& c);
- double getReal() const { return x; }
- double getImag() const { return y; }
- friend Complex add(Complex& c1, Complex& c2);
- };
-
- Complex::Complex(double real, double imag)
- {
- x = real;
- y = imag;
- }
-
- void Complex::assign(Complex& c)
- {
- x = c.x;
- y = c.y;
- }
-
- Complex add(Complex& c1, Complex& c2)
- {
- Complex result(c1);
-
- result.x += c2.x;
- result.y += c2.y;
- return result;
- }
-
- main()
- {
- Complex c1(2, 3);
- Complex c2(5, 7);
- Complex c3;
-
- c3.assign(add(c1, c2));
- cout << "(" << c1.getReal() << " + i" << c1.getImag() << ")"
- << " + "
- << "(" << c2.getReal() << " + i" << c2.getImag() << ")"
- << " = "
- << "(" << c3.getReal() << " + i" << c3.getImag() << ")"
- << "\n\n";
- return 0;
- }
-