流运算符的重载
1.cout 是在iostream 中定義的,是ostream的對象
ostream& ostream::operator<<(int n) {// return *this; } ostream& ostream::operator<<(const char* s) {// return *this; }
2.類似Java中重寫String方法一樣,C++中一般重載“<<”運算符,一般為重載為全局函數
Because:
對輸出運算符的重載
void operator<<(ostream& out) { out << _year << "-" << _month << "-" << _day << endl;
會出現一個問題,只能寫成
d<<cout //打印d中的年月日
因為函數的第一個參數是this指針,第二個參數才是我們傳進去的 out,但是這與std中的cout使用習慣完全不符,我們的所打印變量是應該在cout的右邊,如
cout<<d<<endl
這樣的重載和普通的函數沒有兩樣,也就失去了重載函數的目的所在。
那么這樣,我們便不可以把輸出運算符的重載寫成成員函數,寫成成員函數去實現功能,能實現功能 但失去重載本身的意義。
那么我們在類外寫重載函數,此時輸出運算符的重載函數是一個全局的。
?3.例子
#include <iostream> #include <string> #include <iomanip> #include <cstdlib>using namespace std;class Complex { private:double real;double imag; public:Complex(double r=0.0,double i=0.0):real(r),imag(i){}friend ostream& operator<<(ostream & os,const Complex& c);friend istream& operator>>(istream & is,const Complex& c);//起到聲明friend作用,為全局函數做準備 };ostream& operator<<(ostream& os,const Complex& c) {os<<c.real<<'+'<<c.imag<<'i';return os; }iostream& operator>>(iostream& is,const Complex& c) {string s;is>>s;int pos=s.find("+",0);string sTmp=s.substr(0,pos);c.real=atof(sTmp.c_str());sTmp=s.substr(pos+1,s.length()-pos-2);c.imag=atof(sTmp.c_str());return is; }
?
轉載于:https://www.cnblogs.com/-Asurada-/p/10674249.html
總結
 
                            
                        - 上一篇: 浅谈UWB(超宽带)室内定位技术(转载)
- 下一篇: 求灭开头的成语接龙!
