?? c15_12.cpp
字號:
//重載輸出運算符"<<"
#include <iostream.h > //有些編譯系統可能是包含iostream,并指明名字空間std;
class CComplex
{
public:
CComplex(){ real = 0.0; image = 0.0; }
CComplex(double rv) { real = rv; image = 0.0; }
CComplex(double rv,double iv) { real = rv; image =iv;}
friend CComplex operator + (CComplex c1,CComplex c2);
//作為類的友元函數,重載加運算符,
friend ostream& operator<<(ostream& stream,CComplex c);
//重載輸出運算符"<<"
~CComplex() {};
private:
double real; //復數的實部
double image; //復數的虛部
};
CComplex operator +( CComplex c1,CComplex c2)
{
CComplex temp;
temp.real = c1.real + c2.real;
temp.image = c1.image + c2.image;
return temp;
}
ostream& operator<<(ostream &stream, CComplex c)
{
stream<<"("<<c.real<<"+"<<c.image<<"i)"<<endl;
//以(a+bi)的格式輸出復數
return stream;
}
int main( )
{
CComplex c1(1,5),c2(3);
cout<<"c1="<<c1; //使用重載輸出運算符"<<",輸出復數c1
cout<<"c2="<<c2; //使用重載輸出運算符"<<",輸出復數c2
c1 = c2+16;
cout<<"執行語句c1 = c2+16;之后,";
cout<<"c1="<<c1;
return 0;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -