聲明一個復數類complex,使用友元函數add實現復數的加法-簡單


源程序:

//1.聲明復數的類,complex,使用友元函數 add 實現復數加法。

#include < iostream >

using namespace std;

class Complex

{

private:

  double real, image;

public:

  Complex() {}

  Complex(double a, double b)

  {

    real = a;

    image = b;

  }

  void setRI(double a, double b)

  {

    real = a;

    image = b;

  }

  double getReal()

  {

    return real;

  }

  double getImage()

  {

    return image;

  }

  void print()

  {

    if (image>0)

      cout << "復數:" << real << " + " << image << "i" << endl;

    if (image<0)

      cout << "復數:" << real << " - " << image << "i" << endl;

  }

  friend Complex add(Complex, Complex);//聲明友元函數

};

Complex add(Complex c1, Complex c2)//定義友元函數

{

  Complex c3;

  c3.real = c1.real + c2.real;//訪問 Complex 類中的私有成員

  c3.image = c1.image + c2.image;

  return c3;

}

void main()

{

  Complex c1(19, 0.864), c2, c3;

  c2.setRI(90, 125.012);

  c3 = add(c1, c2);

  cout << "復數一:";

  c1.print();

  cout << "復數二:";

  c2.print();

  cout << "相加后:";

  c3.print();

  system("pause");

}

 

運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM