流输入输出运算符 >> << 比较简单,C++提供了固定的格式,语法上并不是非常难,你只需要记住 istream 和 ostream 这两个类就可以了。本文使用了友元函数方式来实现。具体实现的代码如下,请注意看返回 istream 和 ostream 引用的原因是为了可以使用连续的>>或<<操作符来输入输出。

#include

using namespace std;

class Complex
{
public:
Complex(float x = 0, float y = 0)
:_x(x), _y(y) {}

friend istream& operator>>(istream& is, Complex& another);
friend ostream& operator<<(ostream& os, Complex& another);

private:
float _x;
float _y;
};

istream& operator>>(istream& is, Complex& another)
{
is >> another._x >> another._y;
return is;
}

ostream& operator<<(ostream& os, Complex& another)
{
os << another._x << “ “ << another._y << endl;
return os;
}

int main(int argc, char* argv[])
{
Complex c, c2;
// 考虑连等的情况,实现函数要返回 istream 对象的引用
cin >> c >> c2;
cout << c << c2;

return 0;
}