4.5.2 左移运算符重载
- 作用:可以输出自定义数据类型
#include<iostream>
using namespace std;
class Person
{
public:
//利用成员函数重载 左移运算符 p.operator<<(cout) 简化版本p<<cout
//不会利用成员函数重载<<运算符,因为无法实现 cout在左侧
//void operator<<(cout)
int m_A;
int m_B;
};
//只能利用全局函数左移运算符
ostream & operator<<(ostream& cout, Person& p)//本质 operator<<(cout,p) 简化cout<<p ostream是标准输出流,是cout对象
{
cout << "m_A = " << p.m_A << " m_B = " << p.m_B;
return cout;//添加该句可以实现cout << p<<endl ;否则不能加endl
}
void test01()
{
Person p;
p.m_A = 10;
p.m_B = 10;
cout << p<<endl ;
}
int main()
{
test01();
system("pause");
}
输出: