左移运算符重载
约 25 个字 33 行代码 预计阅读时间不到 1 分钟
Note
重载左移运算符配合友元可以实现输出自定义数据类型
#include <iostream>
using namespace std;
class Person {
friend ostream & operator<<(ostream& out, Person & p);
public :
Person(int a,int b){
this->a = a;
this->b = b;
}
private:
int a,b;
};
ostream& operator << (ostream & out ,Person &p) {
out << "a:" << p.a << " b:" << p.b << endl;
return out;
}
void test(){
Person p1(10,20);
cout << p1 << "hello world" << endl; // 链式编程
}
int main(){
test();
return 0;
}