在重载输出输入运算符的时候,只能采用全局函数的方式(因为我们不能在ostream和istream类中编写成员函数),这里才是友元函数真正的应用场景。对于输出运算符,主要负责打印对象的内容而非控制格式,输出运算符不应该打印换行符;对于输入运算符,必须处理可能失败的情况(通常处理输入失败为默认构造函数的形式),而输出运算符不需要。
#include<iostream>
using namespace std;
class Test {
friend ostream & operator<<(ostream &out, Test &obj);
friend istream & operator >> (istream &in, Test &obj);
public:
Test(int a = , int b = )
{
this->a = a;
this->b = b;
}
void display()
{
cout << "a:" << a << " b:" << b << endl;
}
public: private:
int a;
int b;
};
ostream & operator<<(ostream &out, Test &obj)
{
out << obj.a << " " << obj.b;
return out;
}
istream & operator>>(istream &in, Test &obj)
{
in >> obj.a>> obj.b;
if (!in)
{
obj = Test();
}
return in;
}
int main()
{
Test t1(, );
cout << t1 << endl;
cout << "请输入两个int属性:";
cin >> t1;
cout << t1 << endl;;
cout << "hello world!\n";
return ;
}
输入正确时输入错误时