程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 通過重載輸入和輸出運算符實現復數的輸入和輸出

通過重載輸入和輸出運算符實現復數的輸入和輸出

編輯:C++入門知識

程序代碼:

#include 

using namespace std;

class Complex   
{
public:
      Complex( )//定義默認構造函數初始化復數
      {
          real=0;
          imag=0;
      }      
     
      //使用初始化表初始化復數
      Complex(double r, double i):real(r),imag(i){}
     
      Complex operator+(Complex &c2);//復數的加法
      Complex operator-(Complex &c2);//復數的減法
      Complex operator*(Complex &c2);//復數的乘法
      Complex operator/(Complex &c2);//復數的除法

      //重載<<運算符實現輸出復數
      friend ostream&  operator <<(ostream& output, Complex& c);

       //重載>>運算符實現輸入復數
      friend istream&  operator >>(istream& input, Complex& c);

private:
      double real;//復數的實部
      double imag;//復數的虛部
};

//復數的加法
Complex Complex::operator+(Complex &c2)
{
    Complex c3;

    c3.real  = real + c2.real;
    c3.imag  = imag + c2.imag;

    return c3;
}

//復數的減法
Complex Complex::operator-(Complex &c2)
{
    Complex c3;

    c3.real  = real - c2.real;
    c3.imag  = imag - c2.imag;

    return c3;
}

//復數的乘法
Complex Complex::operator*(Complex &c2)
{
    Complex c3;

    c3.real = real*c2.real - imag * c2.imag;
    c3.imag = real*c2.imag + imag * c2.real;

    return c3;
}

//復數的除法
Complex Complex::operator/(Complex &c2)
{  
    Complex c3;

    c3.real = (real * c2.real + imag * c2.imag) / (c2.real*c2.real + c2.imag * c2.imag);

    c3.imag = (imag * c2.real - real * c2.imag) / (c2.real*c2.real + c2.imag * c2.imag);

    return c3;
}

//重載>>運算符實現輸入復數
istream&  operator >>(istream& input, Complex& c)
{
    int a, b;
    char sign, i;

    do
    {
        cout<<"請輸入一個復數,以(a+bi或a-bi)的形式輸入:";
        input>>a>>sign>>b>>i;

    }while(!(('+' == sign || '-' == sign) && 'i' == i));

   c.real = a;
   c.imag = ('+' == sign) ? b : -b;

   return input;
}

//重載<<運算符實現輸出復數
ostream&  operator <<(ostream& output, Complex& c)
{
    int num = c.imag;

    if(num>0)
    {
        output<>c1;

    cout<<"請輸入一個復數:";
    cin>>c2;

    //打印第一個復數
    cout<<"c1 = ";
    cout<


執行結果:


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved