C++之输入输出运算符重载

cpp 复制代码
friend ostream& operato<<(ostream& os,const RIGHT& right){...}
ostream, 标准库的类
cout << a; //operator<<(cout,a)
cpp 复制代码
friend istream& operato>>(istream& is,RIGHT& right){...}
istream cin;//istream是标准库的类
cin >> a;//operator>>(cin,a)
  • 因为无法向标准库类添加成员函数,所以只能使用全局函数的形式
cpp 复制代码
#include <iostream>
using namespace std;
class Complex{
private:
    double r;
    double i;
public:
    Complex(double r, double i){
        this->r = r;
        this->i = i;
    }
    const Complex operator+(const Complex& c){
        Complex tmp(r+c.r, i+c.i);
        return tmp;
    }
    Complex & operator+=(const Complex &c){
        r = r + c.r;
        i = i + c.i;
        return *this;
    }
    friend ostream& operator<<(ostream &os, const Complex& c){
        os << c.r << " + " << c.i << "i" << endl;
        return os; // cout << a << b << c << endl;
    }
    friend istream& operator>>(istream &is, Complex& c){
        is >> c.r >> c.i ;
        return is;
    }
    friend const Complex operator-(const Complex& l , const Complex& r);
    friend Complex & operator-=(Complex &L, const Complex &R);
};
const Complex operator-(const Complex& l, const Complex& r){
        Complex tmp(l.r - r.r, l.i - r.i);
        return tmp;
}
    Complex & operator-=(Complex &L, const Complex &R){
        L.r -= R.r;
        L.i -= R.i;
        return L;
    }
int main(void){
    Complex c1(2,3);
    cout << c1;
    Complex c2(0,0);
    cin >> c2;
    cout << c2;
    return 0;
}
相关推荐
朽棘不雕6 分钟前
进一步了解模板
c++
汉克老师3 小时前
CSP-J 2026 初赛试题解析(第一部分:选择题(8-15))精讲
c++·csp-j·小学生·学c++编程
wabs6664 小时前
关于二叉树【力扣572.另一棵树的子树的思考】
数据结构·c++·算法·leetcode·二叉树
风合星语5 小时前
2026 ROS 2 Lyrical C++ 入门(五):Action 实战——任务反馈、取消与超时处理
c++·机器人·ros2·异步编程·lyrical
91刘仁德5 小时前
C++ 继承和多态 设计模式
c语言·c++·笔记
库玛西6 小时前
哈夫曼树与前缀编码:数据压缩的贪心核心
c语言·c++·笔记·考研
别动我齐刘海6 小时前
ROS2 Jazzy + C++ 实战路线——进阶学习3
c++·人工智能·vscode·python·算法·机器学习·机器人
0+1116 小时前
算法 --滑动窗口
c++·算法·leetcode
stolentime6 小时前
(有原题)CSP-S2026第一轮试题(附答案解析、markdown源码)
c++·csp
m0_734571767 小时前
深入理解C++ RAII
开发语言·c++