源程序:
/*(文件註釋頭部開始)
*程序的版權和版本聲明部分
*Copyright (c) 2011,煙臺大學計算機學院學生
*All rights reserved.
*文件名稱:字符串中單詞個數的統計
*作 者:2011級計114-3張宗佳
*完成日期:2011年4月14號
*版本號:vc
* 對任務及求解方法的描述部分
* 輸入描術:輸入兩個複數
* 問題描述:在重載運算符+、-、*、/的基礎上,增加重載運算符>> << ,實現輸入和輸出。
* 程序輸出:輸出兩個複數及運算後的結果,使結果看起來更自然。
* 程序頭部的註釋結束
*/
#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 &c2);//聲明“ <<”運算符,定爲友元函數
friend istream& operator >> (istream&, Complex &c2);//聲明友元函數,重載">>"運算符函數
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 &c2)
{
if(c2.imag > 0)
{
output << "(" << c2.real << "+" << c2.imag << "i)" << endl;//實現當imag爲正數時,以3+4i的形式輸出
}
else
{
output << "(" << c2.real << c2.imag << "i)" << endl;
}
return output;
}
istream& operator >> (istream& input, Complex &c2)
{
cout << "輸入複數的實部與虛部:";
input >> c2.real >> c2.imag;
return input;
}
int main()
{
Complex c1,c2,c3;
cin >> c1 >> c2;
cout << "c1=" << c1;
cout << "c2=" << c2;
c3 = c1 + c2;
cout << "c1+c2=" << c3;
c3 = c1 - c2;
cout << "c1-c2=" << c3;
c3 = c1*c2;
cout << "c1*c2=" << c3;
c3 = c1 / c2;
cout << "c1/c2=" << c3;
system("pause");
return 0;
}
實驗結果:
上機感言:
主要是學習重載運算符“<<”">>"函數的定義與調用,定義之後,在調用時可以連續輸入與連續輸出,而且只有在輸出本類中的對象時才能使用重載的運算符,對其他類型的對象是無效的。。。