在重载输出输入运算符的时候,只能采用全局函数的方式(因为我们不能在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 }
输入正确时输入错误时