在重載輸出輸入運算符的時候,只能采用全局函數的方式(因為我們不能在ostream和istream類中編寫成員函數),這里才是友元函數真正的應用場景。對於輸出運算符,主要負責打印對象的內容而非控制格式,輸出運算符不應該打印換行符;對於輸入運算符,必須處理可能失敗的情況(通常處理輸入失敗為默認構造函數的形式),而輸出運算符不需要。
1 #include<iostream>
2 using namespace std; 3 class Test { 4 friend ostream & operator<<(ostream &out, Test &obj); 5 friend istream & operator >> (istream &in, Test &obj); 6 public: 7 Test(int a = 0, int b = 0) 8 { 9 this->a = a; 10 this->b = b; 11 } 12 void display() 13 { 14 cout << "a:" << a << " b:" << b << endl; 15 } 16 public: 17
18
19 private: 20 int a; 21 int b; 22 }; 23 ostream & operator<<(ostream &out, Test &obj) 24 { 25 out << obj.a << " " << obj.b; 26 return out; 27 } 28 istream & operator>>(istream &in, Test &obj) 29 { 30 in >> obj.a>> obj.b; 31 if (!in) 32 { 33 obj = Test(); 34 } 35 return in; 36 } 37 int main() 38 { 39 Test t1(1, 2); 40 cout << t1 << endl; 41 cout << "請輸入兩個int屬性:"; 42 cin >> t1; 43 cout << t1 << endl;; 44 cout << "hello world!\n"; 45 return 0; 46 }
輸入正確時輸入錯誤時