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 天前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境3 天前
C++ 的Eigen 库全解析
c++
卷无止境3 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴3 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18005 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴5 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨6 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint45610 天前
C++进阶(1)——前景提要
c++
夜悊10 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴10 天前
CMake 021: IF 条件判据详诠
c++·cmake