形式:ostream& operator<<(ostream& cout,const Point& p)
或 istream& operator>>(istream& cin,Point& p)
語法:
重載方式:只能使用友元函數(shù)重載 且 使用三個引用&
函數(shù)名:
輸出流:?operator<<(參數(shù)表)
輸入流:operator>>(參數(shù)表)
參數(shù)表:兩個參數(shù)均用引用&(這里需要注意)
輸出流:?必須是兩個參數(shù):對輸出流ostream&和 對象
第一個操作數(shù)cout,定義在文件iostream中,是標準類類型ostream的對象的引用。
如:ostream& cout,const Point& p
輸入流:必須是兩個參數(shù):對輸入流ostream&和 對象
第一個操作數(shù)是cin,定義在文件iostream,實際上是標準類類型istream的對象的引用
如:instream& cin,const Point& p
函數(shù)調(diào)用:
輸出流:?顯式調(diào)用:cout<<對象
隱式調(diào)用:?operator<<(cout,對象)
輸入流:顯式調(diào)用:cin>>對象
隱式調(diào)用:?operator>>(cin,對象)
返回類型:返回類型固定 + 使用返回函數(shù)引用(滿足連續(xù)輸出),之所以返回 istream(或ostream) 類對象的引用,是為了能夠連續(xù)讀?。ɑ蜉敵觯尨a書寫更加漂亮,例如:
(complex c1, c2; cin>>c1>>c2;)
或:cout<<a<<b;它等同于(cout<<a)<<b; (cout<<a)返回cout的引用,即就是它自己,它可以再次作為左值,因而能夠連著寫這個輸出流 。
若寫成ostream operator << (ostream& os, Point& pt);cout<<a<<b;相當于:(cout<<a)<<b;第一個()中返回cout的臨時變量,它不可以作為左值,因而錯誤。
輸出流:?返回ostream&
如:ostream& operator<<(ostream& cout,const Point& p)
輸入流:返回:istream&
如:istream& operator>>(istream& cin,Point& p)
注意:為什么輸入輸出操作符的重載必須使用友元函數(shù)?
因為:成員函數(shù)要求是有對象調(diào)用,則第一個參數(shù)必須是類的對象,但是<<和>>第一個參數(shù)是流的對象引用。故,不能使用成員函數(shù)
引用:http://blog.csdn.net/insistgogo/article/details/6626952