重载流插入运算符“<<”
#include <iostream> using namespace std; class Complex { public: Complex( ) { real=0; imag=0; } Complex(double r,double i) { real=r; imag=i; } Complex operator + (Complex &c2); //运算符“+”重载为成员函数 friend ostream& operator << (ostream&, const Complex&); //运算符“<<”重载为友元函数 private: double real; double imag; }; Complex Complex::operator + (Complex &c2) //定义运算符“+”重载函数 { return Complex(real+c2.real,imag+c2.imag); } ostream& operator << (ostream& output,const Complex& c) //定义运算符“<<”重载函数 { output<<"("<<c.real<<"+"<<c.imag<<"i)"; return output; } int main( ) { Complex c1(2,4),c2(6,10),c3; c3=c1+c2; cout<<c1<<'+'<<c2<<'='<<c3<<endl; return 0; } /* 去掉operator << 中的const后,将不能支持cout<<c1+c2<<endl;式的输出 */
重载流提取运算符“>>”
#include <iostream> using namespace std; class Complex { public: friend ostream& operator << (ostream&,const Complex&); //声明重载运算符“<<” friend istream& operator >> (istream&,Complex&); //声明重载运算符“>>” private: double real; double imag; }; ostream& operator << (ostream& output,const Complex& c) //定义重载运算符“<<” { output<<"("<<c.real<<"+"<<c.imag<<"i)"; return output; } istream& operator >> (istream& input,Complex& c) //定义重载运算符“>>” { cout<<"input real part and imaginary part: "; input>>c.real>>c.imag; return input; } int main( ) { Complex c1,c2; cin>>c1>>c2; cout<<"c1="<<c1<<endl; cout<<"c2="<<c2<<endl; return 0; }
对复数输入输出的完善
#include <iostream> using namespace std; class Complex { public: Complex( ) { real=0; imag=0; } Complex(double r,double i) { real=r; imag=i; } Complex operator + (Complex &c2); //运算符“+”重载为成员函数 friend ostream& operator << (ostream&,const Complex&); //声明重载运算符“<<” friend istream& operator >> (istream&,Complex&); //声明重载运算符“>>” private: double real; double imag; }; Complex Complex::operator + (Complex &c2) //定义运算符“+”重载函数 { return Complex(real+c2.real,imag+c2.imag); } ostream& operator << (ostream& output, const Complex& c) //定义重载运算符“<<” { output<<"("<<c.real; if(c.imag>=0) output<<"+"; //虚部为正数时,在虚部前加“+”号 output<<c.imag<<"i)"; //虚部为负数时,在虚部前不加“+”号 return output; } istream& operator >> (istream& input,Complex& c) //定义重载运算符“>>” { int a,b; char sign,i; do { cout<<"input a complex number(a+bi或a-bi):"; input>>a>>sign>>b>>i; } while(!((sign=='+'||sign=='-')&&i=='i')) c.real=a; c.imag=(sign=='+')?b:-b; return input; } int main( ) { Complex c1,c2(6,10),c3; cin>>c1 cout<<"c1="<<c1<<endl; cout<<"c2="<<c2<<endl c3=c1+c2; cout<<"c1+c2="<<c3<<endl; return 0; }
时间: 2024-09-16 22:10:15