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;
}
相关推荐
艾莉丝努力练剑1 小时前
【Linux网络】Linux 网络编程入门:TCP Socket 编程(下)
linux·运维·服务器·网络·c++·tcp/ip
宵时待雨1 小时前
linux笔记归纳4:进程概念
linux·运维·服务器·c++·笔记
凯瑟琳.奥古斯特1 小时前
力扣2760 C++滑动窗口解法
数据结构·c++·算法·leetcode·职场和发展
ximu_polaris1 小时前
设计模式(C++)-行为型模式-访问者模式
c++·设计模式·访问者模式
血玥珏2 小时前
血玥珏-多WAV/MP3混音合成小工具2.0.0.5
c++·音视频
Shadow(⊙o⊙)2 小时前
初识Qt+经典方式实现hello world!的交互
开发语言·c++·后端·qt·学习
梵尔纳多2 小时前
OpenGL 实例化
c++·图形渲染·opengl
隐士Xbox3 小时前
c++ 指针的用法
开发语言·c++·计算机视觉
salipopl3 小时前
C++ 面试题:C++中 constexpr 函数的限制有哪些?
c++
无限进步_3 小时前
【C++】从红黑树到 map 和 set:封装设计与迭代器实现
开发语言·数据结构·数据库·c++·windows·github·visual studio