问题及代码:
/* *Copyright (c) 2014,烟台大学计算机学院 *All rights reserved. *文件名称:lily.cpp *作者:李莉 *完成日期:2015年5月5日 版本号: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-(); friend ostream& operator<<(ostream& output,const Complex &c); friend istream& operator>>(istream& input,Complex &c); friend Complex operator+(const Complex &c1, Complex &c2); friend Complex operator-(const Complex &c1, Complex &c2); friend Complex operator-(double d1, Complex &c2); friend Complex operator*(const Complex &c1, Complex &c2); friend Complex operator/(const Complex &c1, Complex &c2); void display(); private: double real; double imag; }; ostream& operator<<(ostream&output,const Complex &c) { output<<"("<<c.real; output<<"("<<c.real; if(c.imag>=0) output<<"+"; output<<c.imag<<"i)"; return output; return output; } istream& operator>>(istream& input,Complex &c) { double a,b; char s,i; while(!((s=='-'||s=='+')&&(i=='i'))); { cout<<"请输入一个虚数(a+bi或者a-bi):"<<endl; input>>a>>s>>b>>i; } c.real=a; c.imag=(s=='+')?b:-b; return input; } Complex Complex::operator-() { return (0-*this); } Complex operator+(const Complex &c1, Complex &c2) { Complex c; c.real=c1.real+c2.real; c.imag=c1.imag+c2.imag; return c; } Complex operator-(const Complex &c1, Complex &c2) { Complex c; c.real=c1.real-c2.real; c.imag=c1.imag-c2.imag; return c; } Complex operator-(double d1, Complex &c2) { Complex c(d1,0); return c-c2; } Complex operator*(const Complex &c1, Complex &c2) { Complex c; c.real=c1.real*c2.real-c1.imag*c2.imag; c.imag=c1.imag*c2.real+c1.real*c2.imag; return c; } Complex operator/(const Complex &c1, Complex &c2) { Complex c; c.real=(c1.real*c2.real+c1.imag*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); c.imag=(c1.imag*c2.real-c1.real*c2.imag)/(c2.real*c2.real+c2.imag*c2.imag); return c; } void Complex::display() { cout<<"("<<real<<","<<imag<<")"<<endl; } int main() { Complex c1(3,4),c2(5,-10),c3; cout<<"c1="; c1.display(); cout<<"c2="; c2.display(); c3=c1+c2; cout<<"c1+c2="; c3.display(); c3=c1-c2; cout<<"c1-c2="; c3.display(); c3=c1*c2; cout<<"c1*c2="; c3.display(); c3=c1/c2; cout<<"c1/c2="; c3.display(); return 0; }
运行结果:
心得体会:
自己写完之后差点纠结死啊。。我为什么把输入的时候Complex &c设定成了静态常量,结果给了一个错误就是assignment of menber 'Complex::real' in ready-only object。。郁闷得要死啊。。下次注意。const不能随便用了