在复数类中的运算符重载基础上
(1)再定义一目运算符 -,-c相当于0-c。
(2)定义Complex类中的<<和>>运算符的重载,实现输入和输出,改造原程序中对运算结果显示方式,使程序读起来更自然。
/* * Copyright (c) 2015,烟台大学计算机学院 * All right reserved. * 作者:邵帅 * 文件:Demo.cpp * 完成时间:2015年05月14日 * 版本号:v1.0 */ #include <iostream> using namespace std; class Complex { public: Complex() { real=0; imag=0; } Complex(double r,double i) { real=r; imag=i; } friend ostream& operator << (ostream& output, const Complex& c); friend istream& operator >> (istream& input, Complex& c); Complex operator-(); Complex operator+(const Complex &c2); Complex operator-(const Complex &c2); Complex operator*(const Complex &c2); Complex operator/(const Complex &c2); void display(); private: double real; double 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; } Complex Complex::operator-() { return(-*this); } Complex Complex::operator+(const Complex &c2) { Complex a; a.real=real+c2.real; a.imag=imag+c2.imag; return a; } Complex Complex::operator-(const Complex &c2) { Complex a; a.real=real-c2.real; a.imag=imag-c2.imag; return a; } Complex Complex::operator*(const Complex &c2) { Complex a; a.real=real*c2.real; a.imag=imag*c2.imag; return a; } Complex Complex::operator/(const Complex &c2) { Complex a; a.real=real/c2.real; a.imag=imag/c2.imag; return a; } void Complex::display() { cout<<"("<<real<<","<<imag<<"i)"<<endl; } //下面定义用于测试的main()函数 int main() { Complex c1,c2,c3; cout<<"c1: "<<endl;; cin>>c1; cout<<"c2: "<<endl; cin>>c2; cout<<"c1="<<c1<<endl; cout<<"c2="<<c2<<endl; c3=c1+c2; cout<<"c1+c2="<<c3<<endl; c3=c1-c2; cout<<"c1-c2="<<c3<<endl; c3=c1*c2; cout<<"c1*c2="<<c3<<endl; c3=c1/c2; cout<<"c1/c2="<<c3<<endl; return 0; }
运行结果:
@ Mayuko
时间: 2024-10-03 23:06:39