重载流插入运算符
1 #include <iostream> 2 3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */ 4 using namespace std; 5 class Complex 6 { 7 public: 8 Complex(){ 9 real=0; 10 imag=0; 11 } 12 Complex(double r,double i){ 13 real=r; 14 imag=i; 15 } 16 Complex operator +(Complex &c2); 17 friend ostream&operator<<(ostream&,Complex&); 18 private: 19 double real; 20 double imag; 21 } ; 22 23 Complex Complex::operator +(Complex &c2) 24 { 25 return Complex(real+c2.real,imag+c2.imag); 26 } 27 28 ostream&operator<<(ostream&output,Complex&c) 29 { 30 output<<"("<<c.real<<"+"<<c.imag<<"i)"<<endl; 31 return output; 32 } 33 34 int main(int argc, char** argv) { 35 Complex c1(2,4),c2(6,10),c3; 36 c3=c1+c2; 37 cout<<c3; 38 return 0; 39 }