类和对象-c++运算符重构-左移运算符重载

(1)我们可以通过运算符重构来实现我们想输出形式

using namespace std;
class person{
	public:
		int m_a;
		int m_b;
		
};
ostream & operator<<(ostream &cout,person &p){
	cout<<p.m_a<<endl<<p.m_b;
	return cout; 
}
void test01(){
	person p;
	p.m_a=10;
	p.m_b=10;
	cout<<p<<endl;//这是一个链式传递,每一次都返回cout
}
int main()
{
	test01();
}

(2)一般建议在私有作用域中使用

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: 
		int m_a;
		int m_b;
		
};
ostream & operator<<(ostream &cout,person &p){
	cout<<p.m_a<<endl<<p.m_b;
	return cout; 
}
void test01(){
	person p(10,10);
//	p.m_a=10;
//	p.m_b=10;
	cout<<p<<endl;
}
int main()
{
	test01();
}
全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务