- cout 是 iostream中定义的,ostream类的对象
- “<<”是在iostream中经过了重载
cout << 5 即 cout.operator(5); cout << “this” 即 cout.operator<<(“this”)
ostream & ostream::operator<<(int n) {
... // 输出n的代码
return *this;
}
cout << 5 << “this” 等价于 cout.operator<<(5).operator<<(“this”)
自定义重载
只能重载为全局函数
如果访问私有成员,则声明成友元
class A {
public:
int n;
}
ostream & operator<<(ostream & o, const A a) {
o << s.n;
return o;
}
例题
假定c是Complex的对象,现在希望写“cout << c”,就能以“a+bi”的形式输出;同时希望以“cin >> c”是c接收“a+bi”形式的输入
class Complex {
double real, image;
public:
Complex(double r=0, double i=0):real(r),image(i){}
friend ostream & operator << (ostream & os, const Complex & c);
friend istream & operator >> (istream & s, Complex & c);
}
ostream & operator << (ostream & os, const Complex & c) {
os << c.real << "," << c.image << "i";
return os;
}
istream & operator >> (istream & is, Complex c) {
string s;
is >> s;
int pos = s.find("+", 0);
string sTmp = s.substr(0, pos);
c.real = atof(sTmp.c_str());
sTmp = s.substr(pos+1,s.length()-pos-2);
c.image = atof(sTmp.c_str());
return is;
}