左移运算符的重载可以帮助我们更好的输出自定义的数据类型,可以做到简洁,在不浪费更多代码行的情况下,使用函数,来输出类中的成员属性数据

注意

  1. 成员函数 实现不了 p<<cout不是我们想要的效果
  2. 全局函数实现左移重载 ostresm对象只能有一个

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;

class Person {
public:

int m_A;
int m_B;
};

ostream &operator<< (ostream &cout,Person &p) {
cout << "m_A=" << p.m_A << endl;
cout << "m_B=" << p.m_B << endl;
return cout;
}

int main(){
Person p;
p.m_A = 10;
p.m_B = 20;
cout << p << "hello world" << endl;//链式编程
return 0;
}