C++(运算符重载<<)

左移运算符重载

  • 可以输出自定义数据类型
#include <iostream>

using namespace std;

class Person{
	friend ostream& operator<<(ostream& out,Person &p);
public:
	Person(int a, int b)
	{
		this->m_A=a;
		this->m_B=b;
	}
	//成员函数实现不了 p<<cout
	//void operator<<(Person &p){
	//}
private:
	int m_A;
	int m_B;
};

//全局函数实现左移重载
//ostream对象只能有一个
ostream& operator<<(ostream&cout, Person &p){
	
	cout<<"a:"<<p.m_A<<" b:"<<p.m_B;
	return cout;
}

void test()
{
	Person p1(10,20);
	cout<<p1<<" hello world "<<endl; //链式编程
}


int main(void)
{	
	test();
	return 0;
}
  • 总结:重载运算符配合友元可以实现输出自定义数据类型。
posted @ 2021-01-20 12:12  flyingswallow  阅读(198)  评论(0编辑  收藏  举报