home *** CD-ROM | disk | FTP | other *** search
/ C Programming Starter Kit 2.0 / SamsPublishing-CProgrammingStarterKit-v2.0-Win31.iso / tybc4 / class5.cpp < prev    next >
C/C++ Source or Header  |  1993-03-31  |  1KB  |  56 lines

  1. // Program demonstrates friend functions
  2.  
  3. #include <iostream.h>
  4.  
  5. class Complex
  6. {
  7.    protected:
  8.      double x;
  9.      double y;
  10.  
  11.    public:
  12.      Complex(double real = 0, double imag = 0);
  13.      Complex(Complex& c) { assign(c); }
  14.      void assign(Complex& c);
  15.      double getReal() const { return x; }
  16.      double getImag() const { return y; }
  17.      friend Complex add(Complex& c1, Complex& c2);
  18. };
  19.  
  20. Complex::Complex(double real, double imag)
  21. {
  22.   x = real;
  23.   y = imag;
  24. }
  25.  
  26. void Complex::assign(Complex& c)
  27. {
  28.   x = c.x;
  29.   y = c.y;
  30. }
  31.  
  32. Complex add(Complex& c1, Complex& c2)
  33. {
  34.   Complex result(c1);
  35.  
  36.   result.x += c2.x;
  37.   result.y += c2.y;
  38.   return result;
  39. }
  40.  
  41. main()
  42. {
  43.   Complex c1(2, 3);
  44.   Complex c2(5, 7);
  45.   Complex c3;
  46.  
  47.   c3.assign(add(c1, c2));
  48.   cout << "(" << c1.getReal() << " + i" << c1.getImag() << ")"
  49.        << " + "
  50.        << "(" << c2.getReal() << " + i" << c2.getImag() << ")"
  51.        << " = "
  52.        << "(" << c3.getReal() << " + i" << c3.getImag() << ")"
  53.        << "\n\n";
  54.   return 0;
  55. }
  56.