C++学习3:C++输入/输出(<<和>>)运算符重载

前言

首先晒一个标准输入输出格式的表格,这些算是命令还是标志位还是操作符呢?

C++输入输出标准库提供了“>>”和“<<”运算符执行输入、输出操作,但标准库只定义了基本数据类型的输入、输出操作,若要直接对类对象进行输入、输出,则需要在类中重载这两个运算符。与其他运算符不同的是,输入、输出运算符只能重载成类的友元函数。“<<”和“>>”运算符重载的格式如下:

ostream& operator<<(ostream&, const 类对象引用);     //输出运算符重载 
istream& operator>>(istream&, 类对象引用);            //输入运算符重载 

 输出运算符“<<”重载的第一个参数是ostream对象引用,该对象引用不能使用const修饰,第二个参数是输出对象的const引用。输入运算符“>>”重载的第一个参数是istream对象引用,第二个参数是要向其中存入数据的对象,该对象不能使用const修饰。

下面通过案例演示输入/输出运算符重载的用法:

#include <iostream>
#include <iomanip>
using namespace std;

class myclass{
    friend ostream& operator<<(ostream &o,const myclass &c);
    friend istream& operator>>(istream &i,myclass &c);
public:
    myclass(int n):num(n){
        cout << "class init" << endl;
    }
    ~myclass(){
        cout << "class destroy" << endl;
    }
    void show(){
        cout << "num = " << num << endl;
    }
private:
    int num;
};
ostream& operator<<(ostream &o,const myclass &c){
    o << c.num;
    return o;
}
istream& operator>>(istream &i,myclass &c){
    i >> c.num;
    return i;
}

int main()
{
    myclass c(10);
    cout << c << endl;
    cin >> c;
    c.show();
    return 0;
}

执行结果:调用了cin,所以测试时输入一个数字,如下所示,输入20,调用show函数后输出20.

class init
10
20
num = 20
class destroy

 小结

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

千册

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值