1.将输入输出流重载为成员函数
#include<iostream>
#include<iomanip>
using namespace std;
class A
{
private:
int a,b;
public:
istream &operator >>(istream &in);
ostream &operator <<(ostream &out);
};
int main()
{
A x;
x>>cin;//成员函数
cout<<"---------------"<<endl;
x<<cout;//成员函数
}
istream &A::operator >>(istream &in)
{
in>>a>>b;
return in;
}
ostream &A::operator <<(ostream &out)
{
out<<a<<setw(5)<<b<<endl;
return out;
}
输出:
2.将输入输出流重载为友元函数。
#include<iostream>
#include<iomanip>
using namespace std;
class A;
istream &operator >>(istream &in,A &t);
ostream &operator <<(ostream &out,A &t);
class A
{
private:
int a,b;
public:
friend istream &operator >>(istream &in,A &t);
friend ostream &operator <<(ostream &out,A &t);
};
int main()
{
A x;
cin>>x;//友元函数
cout<<"---------------"<<endl;
cout<<x;//友元函数
}
istream &operator >>(istream &in,A &t)
{
in>>t.a>>t.b;
return in;
}
ostream &operator <<(ostream &out,A &t)
{
out<<t.a<<setw(5)<<t.b<<endl;
return out;
}
输出:
我是小白,欢迎指正,感激不尽!