在C++里,cout 后边加上<< 便可以输出数据,但是输出的只是一些变量,我现在想输出一个对象,所以需要重载一下<<。
例如我创建了一个class person{ }; person p;
class person
{
public:
int 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;;
}