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;
}
相关推荐
晚风吹红霞24 分钟前
深入浅出 STL 之 map 与 set:从入门到实战
开发语言·c++
牛油果子哥q28 分钟前
【C++封装】C++封装思想与访问权限终极精讲:public/private/protected权限解析、类封装设计、继承权限变化、工程私有化规范与面试坑点
c++·面试
织梦旅途28 分钟前
C++ 第一课 从 Hello Word!立刻开始
c++
.千余32 分钟前
【C++】 String 常用操作:增删查改 | 查找 | 截取 | IO
java·服务器·开发语言·c++·笔记·学习
jelly酱35 分钟前
Qt 坐标体系入门:从 GUI 概念到坐标实践
c++
代码改善世界35 分钟前
【C++进阶】哈希表封装unordered_map和unordered_set
c++·哈希算法·散列表
c2385638 分钟前
C++ lambda 表达式详细介绍
开发语言·c++
无忧.芙桃1 小时前
debug实例与分析(一)
开发语言·c++·算法
alwaysrun1 小时前
C++之类型安全格式化format
c++·程序员·编程语言
邪修king1 小时前
C++ 哈希表超全详解:从底层实现到封装 myunordered_map/myunordered_set
c++·哈希算法·散列表