重载左移运算符

#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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值