/* * 程序的版权和版本声明部分 * Copyright (c)2013, 烟台大学计算机学院学生 * All rightsreserved. * 文件名称: object.cpp * 作者:杨绍宁 * 完成日期: 2013年 4 月 26日 * 版本号: v1.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); Complex operator*(Complex &c2); Complex operator/(Complex &c2); friend Complex operator-(Complex &c1,Complex &c2); friend istream& operator>>(istream&,Complex&); friend ostream& operator<<(ostream&,Complex&); void display(); private: double real; double imag; }; istream& operator>>(istream& input,Complex&c) { input>>c.real>>c.imag; return input; } ostream& operator<<(ostream&output,Complex&c) { output<<"("<<c.real<<","<<c.imag<<"i)"; } Complex Complex::operator+(Complex &c2) { Complex c; c.real=real+c2.real; c.imag=imag+c2.imag; return c; } Complex Complex::operator*(Complex &c2) { Complex c; c.real=real*c2.real-imag*c2.imag; c.imag=imag*c2.real+real*c2.imag; return c; } Complex Complex::operator/(Complex &c2) { Complex c; double d; d=c2.real*c2.real+c2.imag*c2.imag; c.real=(real*c2.real+imag*c2.imag)/d; c.imag=(-real*c2.imag+imag*c2.real)/d; return c; } Complex operator-(Complex &c1,Complex &c2) { Complex c; c.real=c1.real-c2.real; c.imag=c1.imag-c2.imag; return c; } void Complex::display() { cout<<"("<<real<<","<<imag<<"i"<<")"<<endl; } int main() { Complex c1,c2,c3; cin>>c1>>c2; cout<<"c1="; cout<<c1<<endl; cout<<"c2="; cout<<c2<<endl; c3=c1+c2; cout<<"c1+c2="; cout<<c3<<endl; c3=c1-c2; cout<<"c1-c2="; cout<<c3<<endl; c3=c1*c2; cout<<"c1*c2="; cout<<c3<<endl; c3=c1/c2; cout<<"c1/c2="; cout<<c3<<endl; return 0; }
感受:重载流提取运算符>>,使问题简单啊