/* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱:
* 作 者: 苗影
* 完成日期: 2012 年 4 月 15 日
* 版 本 號:
* 對任務及求解方法的描述部分
* 輸入描述:
* 問題描述:
* 程序輸出:
* 程序頭部的註釋結束
*/
#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&);//聲明重載運算符“<<”函數
private:
double real;
double imag;
};
//下面定義成員函數
Complex Complex::operator + (Complex &c2)
{
return Complex(real + c2.real,imag + c2.imag);
}
Complex Complex::operator - (Complex &c2)
{
return Complex(real - c2.real,imag - c2.imag);
}
Complex Complex::operator * (Complex &c2)
{
return Complex(real * c2.real - imag * c2.imag,imag * c2.real + real * c2.imag);
}
Complex Complex::operator / (Complex &c2)
{
return Complex((real*c2.real+imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag),
(imag*c2.real-real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag));
}
ostream& operator << (ostream& output,Complex& c)//定義重載運算符“<<”函數
{
output << "(" << c.real << "," << c.imag << "i)" << endl;
return output;
}
void main()
{
Complex c1(3,4),c2(5,-10),c3;
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");
}
感言:因爲已經給了數據,不用在設置cin