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;
}