流运算符的重载

代码

#include <iostream>
#include <string>

using namespace std;

class Er {
public:
    int e01;
    string e02;

    Er &operator>>(unsigned int x) {
        this->e01 >>= x;
        return *this;
    }

    Er &operator<<(unsigned int x) {
        this->e01 <<= x;
        return *this;
    }

    istream &operator<<(istream &is) {
        is >> this->e01;
        is >> this->e02;
        return is;
    }
};

ostream &operator<<(ostream &os, const Er &e) {
    return os << '{' << e.e01 << ";" << e.e02 << '}';
}

int main() {
    Er e = {2, "hello"};
    /* 重载的移位运算符 */
    e << 2;
    cout << e << endl;
    /* 重载的输入流运算 */
    e << cin;
    /* 重载的输出流运算 */
    cout << e << endl;;
    return 0;
}

适配重载运算符的查找规则

在这里插入图片描述

参考文献

C++程序设计语言第4版,458页

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值