重载左移运算符
#include <iostream>
#include <stdio.h>
using namespace std;
class Person{
friend ostream& operator<<(ostream &cout, Person &p);
public:
Person(int a, int b){
m_A = a;
m_B = b;
}
private:
int m_A;
int m_B;
};
ostream& operator<<(ostream &cout, Person &p){
printf("m_A = %d, m_B = %d", p.m_A, p.m_B);
return cout;
}
void test01(){
Person p1(100, 123);
cout << p1 << endl;
}
int main(){
test01();
return 0;
}
如果利用成员函数重载左移运算符 , 则写为
p.operator<< (cout) // 简化版本 p << cout
我们不这么写因为无法实现让cout放在左侧
那么要想将cout放在左侧需要用全局函数重载左移运算符,完成打印类的功能。主要函数如下:
ostream& operator<<(ostream &cout, Person &p){
printf("m_A = %d, m_B = %d", p.m_A, p.m_B);
return cout;
}
这里第一个参数为cout,cout时ostream类型,因为不可以自己构造一个标准输出流对象,我们使用引用的方式传递进来,而第二个参数为Person类,同样使用引用的方式传递,为了让这种重载方式能够像cout << xxx << endl <<<....一样链式进行计算,需要返回一个cout相同类型的对象,此时也就是ostream&。以上代码输出结果如下:
>>> m_A = 123, m_B = 456

浙公网安备 33010602011771号