在C++种,常用到左移运算符:例如 cout <<"Hello World <<endl;
左移运算符重载的的作用:可以输出自定义数据类型
具体示例代码如下:
#include<iostream>
using namespace std;
//左移运算符重载
class Person
{
//友元:
friend ostream &operator<<(ostream &out, Person &p);
public:
Person()
{
m_A = 10;
m_B = 20;
}
private:
int m_A;
int m_B;
};
ostream &operator<<(ostream &out, Person &p)
{
out << "m_A = " << p.m_A <<" " << "m_B = " << p.m_B << endl;
return out;
}
void test()
{
Person p;
cout << p;
}
int main()
{
test();
system("pause");
return 0;
}
总结:重载左移运算符配合友元可以实现输出自定义数据类型