前言
功能和java中重写toString方法一样,下面附上一个简单的代码实现"<<"的重载
#include<iostream>
using namespace std;
class Person
{
public:
int age;
Person(int a):age(a){}
};
//重载"<<"函数,返回值为ostream
ostream& operator<<(ostream &out, Person &p1)
{
cout <<"person age :"<< p1.age << endl;
return out;
}
int main()
{
Person p1(1);
cout << p1.age << endl;
cout << p1 << endl;
return 0;
}
运行结果:
1
person age :1
可以说明Person重载了"<<"函数,可以使用对象名直接调用
参考文献:
C++运算符重载