一个问题

4.PNG

流插入和流提取运算符的重载

以流插入运算符为例
5.PNG
6.PNG
7.PNG
8.PNG
9.PNG

两道例题

10.PNG

  1. //补写代码如下
  2. //因为ostream类和istream类在头文件iostream中已经被c++设计者们设计好,无法修改,所以无法
  3. //再写一个新的流插入运算符重载成员函数
  4. //只能写一个新的流插入运算符重载全局函数
  5. ostream& operator<<(ostream &os,const CStudent &c)
  6. {
  7. os<<s.nAge;
  8. return os;
  9. }

11.PNG

  1. #include <bits/stdc++.h>
  2. #define ASCII0 48
  3. using namespace std;
  4. class Complex
  5. {
  6. private:
  7. int real;
  8. int imag;
  9. public:
  10. Complex(int r = 0, int i = 0) : real(r), imag(i){};
  11. friend istream &operator>>(istream &is, Complex &c);
  12. friend ostream &operator<<(ostream &os, const Complex &c);
  13. };
  14. istream &operator>>(istream &is, Complex &c)
  15. {
  16. char str[10];
  17. is >> str;
  18. int x = 0;
  19. bool b = 1;
  20. for (int i = 0; i < strlen(str); i++)
  21. {
  22. if (str[i] >= '0' && str[i] <= '9')
  23. x = x * 10 + (int)(str[i] - ASCII0);
  24. else
  25. {
  26. if (b)
  27. {
  28. c.real = x;
  29. x = b = 0;
  30. }
  31. else
  32. {
  33. c.imag = x;
  34. x = 0;
  35. }
  36. }
  37. }
  38. return is;
  39. }
  40. ostream &operator<<(ostream &os, const Complex &c)
  41. {
  42. os << c.real << " + " << c.imag << "i ";
  43. return os;
  44. }
  45. int main(void)
  46. {
  47. int n = 0;
  48. Complex c;
  49. cin >> c >> n;
  50. cout << c << n;
  51. return 0;
  52. }