C++学习之左移运算符重载

在C++里,cout 后边加上<< 便可以输出数据,但是输出的只是一些变量,我现在想输出一个对象,所以需要重载一下<<。

例如我创建了一个class person{ }; person p;

class person
{ 
  publicint m_a=10;
};  

void main()
{
  person p;
  cout<<p.m_a;  //这样是可以输出10的
  cout<<p;    // 这样该如何输出??
}
<< 重载后的代码如下:
#include<iostream>
#include<string>
using namespace std;  //这个库里边包含了cout的定义

class Person
{
public:

	Person()
	{
		m_age = new int(18);
		m_name = new string("xcl");
	}		

	/*void operator<<(ostream& out)
	{
		out << "名字:" << *m_name << " 年龄:" << *m_age << endl;
	}*/ 
    //最终变成了p.operator<<(cout); 也就是p<<cout;与我们想的顺序不符

	~Person()
	{	
		if (m_age != NULL)
		{
			delete m_age;
			m_age = NULL;
		}

		if (m_name != NULL)
		{
			delete m_name;
			m_name = NULL;
		}
		cout << "析构函数" << endl;
	}


public:
	string* m_name;
	int* m_age;

};


//参数的顺序不一样会发生重载: p<<cout
//void operator<<(Person& p, ostream& out)
//{
//	out << "名字:" << *p.m_name << " 年龄:" << *p.m_age << endl;
//}

//参数的顺序不一样会发生重载: cout<<p;
//void operator<<(ostream& out, Person& p)
//{
//	out << "名字:" << *p.m_name << " 年龄:" << *p.m_age << endl;
//}


//返回cout这个对象,便可以多次往后追加数据输出。即链式编程
ostream& operator<<(ostream& out, Person& p)//本质operator<<(out,p)   最终简化成out<<p
{
	out << "名字:" << *p.m_name << " 年龄:" << *p.m_age << endl;
	return out;
}

void  main()
{
	Person p;
	//p<<cout;
	cout << p << p<<endl;;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值