#include<iostream>
#include<string>
using namespace std;
//左移运算符重载 <<
//重载左移运算符配合友元可以实现输出自定义数据类型
class person
{
friend ostream& operator<<(ostream& cout, person p);
public:
person(int a, int b) //有参构造函数
{
m_A = a;
m_B = b;
}
private:
//不可以利用成员函数重载<<运算符 因为无法实现 cout在左侧
//void operator<<(person &p)
int m_A;
int m_B;
};
//只能利用全局函数重载左移运算符
ostream& operator<<(ostream& cout, person p)//本质 operator<<(cout,p) 简化cout <<p
{
cout << "m_A= " << p.m_A << "m_B= " << p.m_B << endl;
return cout;
}
void test01()
{
person p(10,20);
cout << p << endl;
}
int main()
{
test01();
system("pause");//按任意键继续
return 0;//关闭程序
}
40类和对象-C++运算符重载-左移运算符重载
最新推荐文章于 2024-09-02 20:21:30 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)