总结:重载左移运算符配合友元可以实现输出自定义数据类型
#include
using namespace std;
class Person {
private:
int m_A;
int m_B;
public:
friend ostream& operator<<(ostream& out, Person& p);
Person(int a, int b)
{
this->m_A = a;
this->m_B = b;
}
//成员函数实现不了 p<
//void operactor <<(Person &p)
};
//全局函数实现左移重载
//ostream对象左移只能有一个
ostream& operator<<(ostream& out, Person& p) { //ostream是输出流 out可以是任何变量,使用引用取别名
out << "a:" << p.m_A << " b:" << p.m_B;
return out;
}
void test() {
Person p1(10, 20);
cout << p1 << "hello world " << endl; //链式编程
}
int main()
{
test();
return 0;
}