?? 例10.7.txt
字號(hào):
例10.7 在例10.2的基礎(chǔ)上,用重載的“<<”輸出復(fù)數(shù)。
#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); //運(yùn)算符“+”重載為成員函數(shù)
friend ostream& operator << (ostream&,Complex&); //運(yùn)算符“<<”重載為友元函數(shù)
private:
double real;
double imag;
};
Complex Complex∷operator + (Complex &c2) //定義運(yùn)算符“+”重載函數(shù)
{return Complex(real+c2.real,imag+c2.imag);}
ostream& operator << (ostream& output,Complex& c) //定義運(yùn)算符“<<”重載函數(shù)
{output<<″(″<<c.real<<″+″<<c.imag<<″i)″<<endl;
return output;
}
int main( )
{Complex c1(2,4),c2(6,10),c3;
c3=c1+c2;
cout<<c3;
return 0;
}
(在Visual C++ 6.0環(huán)境下運(yùn)行時(shí),需將第一行改為#include <iostream.h>,并刪去第2行。)
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -