C++重载流插入和流输出运算符
demo:
/* Name: 重载输入输出流运算符使力代码 Copyright: qianshou Author: zhaozhe Date: 07/12/13 00:11 Description: 首先定义一个复数类,然后重载输入,输出运算符 以及+运算符,以实现复数的输出,相加和输出操作 */ #include<iostream> using namespace std; class Complex { public: Complex(){real=0;imag=0;} Complex(double r,double i) { real=r; imag=i; } friend Complex operator+(Complex &c1,Complex &c2); friend ostream & operator << (ostream &output,Complex &c); friend istream & operator >> (istream &input ,Complex &c); private: double real; double imag; }; Complex operator+(Complex &c1,Complex &c2) { return Complex(c1.real+c2.real,c1.imag+c2.imag); } ostream & operator << (ostream &output,Complex &c) { output<<"("<<c.real<<","<<c.imag<<")"<<endl; return output; } istream & operator >> (istream &input ,Complex &c) { input>>c.real>>c.imag; return input; } int main() { Complex c1,c2,c3; cout<<"please input c1:"; cin>>c1; cout<<"please input c2:"; cin>>c2; c3=c1+c2; cout<<"c3=c1+c2"<<endl; cout<<"c1:"<<c1; cout<<"c2:"<<c2; cout<<"c3=c1+c2"<<endl; cout<<"c3:"<<c3; return 0; }
print:
/* please input c1:3 5 please input c2:2 -1 c3=c1+c2 c1:(3,5) c2:(2,-1) c3=c1+c2 c3:(5,4) */