重载 左移 运算符代码示例
//重载 左移 运算符代码示例:
#include<iostream>
using namespace std;
class person {
public:
int m_A;
int m_B;
//public:
// //成员函数不能实现 << 的重载理由:
// ostream& operator<< (ostream &cout ) {//重载后是:p << cout
// ;
// return cout;
// }
};
//全局函数实现 左移运算符的重载:
ostream& operator<<(ostream& cout, person &p) { //简化后为:cout << p
cout << "p->m_A = " << p.m_A << endl;
cout << "p->m_B = " << p.m_B << endl;
return cout;
}
void test_01() {
person p1;
p1.m_A = 10;
p1.m_B = 10;
person p2;
p2.m_A = 10;
p2.m_B = 10;
cout << p1 << endl;
cout << p2 << endl;
}
int main() {
test_01();
return 0;
}
结果: