2012C++程序設計實驗報告【9.1】

/* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱:        運算符的重載                
* 作    者:      王琳                      
* 完成日期:    2012     年 4    月   16日
* 版 本 號:    9-1

* 對任務及求解方法的描述部分
* 問題描述:接第8周任務2,定義Complex類中的<<和>>運算符的重載,實現輸入和輸出,改造原程序中對運算結果顯示方式,使程序讀起來更自然。

* 程序頭部的註釋結束
*/

源程序:

#include<iostream>  

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 & ,Complex & );
	friend istream & operator >> ( istream & ,Complex &);
private:  
    double real;  
    double imag;  
};  
//下面定義成員函數  
istream& operator >> (istream & input,Complex & c)
{ 
	input>>c.real>>c.imag;
	return input;
}

ostream& operator << (ostream & output,Complex & c)
{
	output<<"("<<c.real<<", "<<c.imag<<"i)"<<endl;
	return output;
}

Complex Complex::operator+(Complex &c2)      
{    
    Complex c;     
    c.real=real+c2.real;    
    c.imag=imag+c2.imag;    
    return c;    
}    
       
Complex Complex::operator-(Complex &c2)        
{        
    Complex c;        
    c.real=real-c2.real;        
    c.imag=imag-c2.imag;        
    return c;        
}        
  
Complex Complex::operator*(Complex &c2)   
{        
    Complex  c;        
    c.real=real*c2.real-imag*c2.imag;        
    c.imag=imag*c2.real+real*c2.imag;        
    return c;        
}        

Complex Complex::operator/(Complex &c2)   
{        
    Complex  c;        
    double d=c2.real*c2.real+c2.imag*c2.imag;    
    c.real=(real*c2.real+imag*c2.imag)/d;     
    c.imag=(imag*c2.real-real*c2.imag)/d;        
    return c;        
}     

int main()  
{  
    Complex c1,c2,c3; 
	cout<<"請輸入複數c1的值:(以a ,b的形式輸入)";
	cin>>c1;
	cout<<"請輸入複數c2的值:(以a ,b的形式輸入)";
	cin>>c2;
    cout<<"c1=";  
    cout<<c1;  
    cout<<"c2=";  
    cout<<c2;  
    c3=c1+c2;  
    cout<<"c1+c2=";  
    cout<<c3;  
    c3=c1-c2;  
    cout<<"c1-c2=";  
    cout<<c3;  
    c3=c1*c2;  
    cout<<"c1*c2=";  
    cout<<c3;  
    c3=c1/c2;  
    cout<<"c1/c2=";  
    cout<<c3;   
	system ("PAUSE");
    return 0;  
}  


運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章