• cout iostream中定义的,ostream类的对象
    • “<<”是在iostream中经过了重载
  • cout << 5cout.operator(5); cout << “this”cout.operator<<(“this”)

    1. ostream & ostream::operator<<(int n) {
    2. ... // 输出n的代码
    3. return *this;
    4. }
  • cout << 5 << “this” 等价于 cout.operator<<(5).operator<<(“this”)

    自定义重载

  • 只能重载为全局函数

    • 如果访问私有成员,则声明成友元

      1. class A {
      2. public:
      3. int n;
      4. }
      5. ostream & operator<<(ostream & o, const A a) {
      6. o << s.n;
      7. return o;
      8. }

      例题

      假定cComplex的对象,现在希望写“cout << c”,就能以“a+bi”的形式输出;同时希望以“cin >> c”是c接收“a+bi”形式的输入

      1. class Complex {
      2. double real, image;
      3. public:
      4. Complex(double r=0, double i=0):real(r),image(i){}
      5. friend ostream & operator << (ostream & os, const Complex & c);
      6. friend istream & operator >> (istream & s, Complex & c);
      7. }
      8. ostream & operator << (ostream & os, const Complex & c) {
      9. os << c.real << "," << c.image << "i";
      10. return os;
      11. }
      12. istream & operator >> (istream & is, Complex c) {
      13. string s;
      14. is >> s;
      15. int pos = s.find("+", 0);
      16. string sTmp = s.substr(0, pos);
      17. c.real = atof(sTmp.c_str());
      18. sTmp = s.substr(pos+1,s.length()-pos-2);
      19. c.image = atof(sTmp.c_str());
      20. return is;
      21. }