- 函數定義期望
- 通過cout<<對象,打印出復數的實部和虛部,這樣一來,就需要重載cout類的位移<<運算函數,但是我們並不能拿到cout源碼,在visual studio我們看到的也僅僅是他的定義
- 若想訪問c1的私有屬性,則應當聲明為友元函數
- 通過定義可以看出cout類的返回值是ostream類型的變量out
void operator<<(ostream &out, cplxaddself &c1) { out << "陳培昌" << endl; out << c1.a << "+" << c1.b<<"i" << endl; }
- 類定義
#include <iostream> #include<string.h> using namespace std; class cplxaddself { public: friend void operator<<(ostream &out, cplxaddself &c1); cplxaddself::cplxaddself(int a,int b) { this->a = a; this->b = b; } void printmyself() { cout <<"復數:"<< this->a << "+" << this->b << "i" << endl; } private: int a; int b; };
- 主函數文件
void main() { cplxaddself c1(4, 6),c3(0,0); cplxaddself c2 = c1; cout << c2; system("pause"); }
輸出結果:
皆大歡喜,.......不過,要是以為事情結束那就太簡單了
如果我們稍加修改就報錯了,其實真正實現的理想方案是滿足鏈式編程
void main() { cplxaddself c1(4, 6),c3(0,0); cplxaddself c2 = c1; cout << c2<<endl;//報錯 system("pause"); }
所以位移運算需要重載為
ostream& operator<<(ostream &out,cplxaddself &cplx) { out << "queen of rain" << endl; out << cplx.a << "+" << cplx.b << "i" << endl; return out; }
void main() { cplxaddself c1(4, 6),c3(0,0); cplxaddself c2 = c1; c1++; cout <<"before:"<< c2<<" after: "<<c1; system("pause"); }
輸出結果: