对于流操作运算符我们需要注意的是函数的返回类型应该是流输入类型的引用或者流输出类型的引用,因为如果代码是
cout<<a<<b;
我们对a执行完cout函数之后,我们应该再次将cout返回给b,使b也能正确的被调用。
#include <iostream>
using namespace std;
class CFraction
{
public:
CFraction()
{
nume = 0;
deno = 1;
}
friend ostream &operator<<(ostream &, CFraction c);
friend istream &operator>>(istream &, CFraction &c);
private:
int nume;
int deno;
};
ostream & operator<<(ostream &output,CFraction c)
{
output << c.nume << "/" << c.deno << endl;
return output;
}
istream & operator>>(istream &input,CFraction &c)
{
input >> c.nume >> c.deno;
return input;
}
int main()
{
CFraction c;
cin >> c;
cout << c;
system("pause");
return 0;
}