第九周實驗報告(任務1)

程序頭部註釋開始
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱: 複數運算符重載  
* 作    者:     郭廣建                       
* 完成日期:  2012年    04  月   22   日
* 版 本 號:  1.0

源程序:

#include<iostream>

using namespace std;

class Complex
{
public:
    Complex(){real=0;imag=0;}
    Complex(double r,double i){real=r;imag=i;}
	friend istream &operator>>(istream &input,Complex &c2);
	friend ostream &operator<<(ostream &output,Complex &c2);
    friend Complex operator+(double d,Complex &c2);
    friend Complex operator-(double d,Complex &c2);
    friend Complex operator*(double d,Complex &c2);
    friend Complex operator/(double d,Complex &c2);
    friend Complex operator+(Complex &c2,double d);
    friend Complex operator-(Complex &c2,double d);
    friend Complex operator*(Complex &c2,double d);
    friend Complex operator/(Complex &c2,double d);
    void display();
private:
    double real;
    double imag;
};
//下面定義成員函數
istream &operator>>(istream &input,Complex &c2)
{
	input >>c2.real >> c2.imag ;

	return input;
}
ostream &operator<<(ostream &output,Complex &c2)
{
	output << '(' << c2.real << ',' << c2.imag <<')' <<endl;

	return output;
}
Complex operator+(double d, Complex &c2)
{
	return Complex(d + c2.real , c2.imag);
}
Complex operator-(double d, Complex &c2)
{
	return Complex(d - c2.real , c2.imag);
}
Complex operator*(double d, Complex &c2)
{
	return Complex( d * c2.real ,d * c2.imag);
}
Complex operator/(double d, Complex &c2)
{
	return Complex(d / c2.real ,d / c2.imag);
}
Complex operator+(Complex &c2,double d)
{
	return Complex(c2.real+d, c2.imag);
}
Complex operator-(Complex &c2,double d)
{
	return Complex(c2.real-d, c2.imag);
}
Complex operator*(Complex &c2,double d)
{
	return Complex(c2.real*d ,c2.imag*d);
}
Complex operator/(Complex &c2,double d)
{
    return Complex(c2.real/d , c2.imag/d);
}
void Complex::display()
{
	cout << '(' << real << ',' << imag << ')' <<endl;
} 
int main()
{
    double d = 3.14;
    Complex c1,c2,c3;
	cin >> c1 >> c2 ;
    cout<<"c1=" << c1;
    cout<<"c2=" << c2;
    c3=d+c1;
    cout<<"d+c1";
    cout << c3;
    c3=d-c1;
    cout<<"d-c1";
    c3.display();
    c3=d*c1;
    cout<<"d*c1";
    c3.display();
    c3=d/c1;
    cout<<"d/c2=";
    c3.display();
	c3=c2+d;
    cout<<"c2+d=";
    c3.display();
    c3=c2-d;
    cout<<"c2-d=";
    c3.display();
    c3=c2*d;
    cout<<"c2*d=";
    c3.display();
    c3=c2/d;
    cout<<"c2/d=";
    c3.display();  
    system("pause");
    return 0;
}


運行結果:

知識積累: 綜合到任務3
發佈了60 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章