第九周任务一 复数 输入输出运算符的重载

来源:互联网 发布:编程就业培训机构 编辑:程序博客网 时间:2024/05/17 22:51
/* (程序头部注释开始)* 程序的版权和版本声明部分* Copyright (c) 2011, 烟台大学计算机学院学生 * All rights reserved.* 文件名称: * 作    者:  姜雅明  * 完成日期:  2012    年   04    月   17    日* 版 本 号:  1.0* 对任务及求解方法的描述部分* 输入描述: 输入一个复数* 问题描述: 复数的四则运算* 程序输出: 运算后的值* 程序头部的注释结束*/#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 Complex operator - (Complex &c1, Complex &c2);friend Complex operator * (Complex &c1, Complex &c2);friend Complex operator / (Complex &c1, Complex &c2);friend ostream & operator << (ostream &output, Complex &c);friend istream & operator >> (istream &iutput, Complex &c);private:double real;double imag;};//下面定义成员函数Complex operator + (Complex &c1, Complex &c2){return Complex (c1.real + c2.real, c1.imag + c2.imag);}Complex operator - (Complex &c1, Complex &c2){return Complex (c1.real - c2.real, c1.imag - c2.imag);}Complex operator * (Complex &c1, Complex &c2){return Complex (c1.real * c2.real - c1.imag * c2.imag, c1.imag * c2.real + c1.real * c2.imag);}Complex operator / (Complex &c1, Complex &c2){return Complex ((c1.real * c2.real + c1.imag * c2.imag) / (c2.imag * c2.imag + c2.real * c2.real),(c1.imag * c2.real - c1.real * c2.imag) / (c2.imag * c2.imag + c2.real * c2.real));}ostream & operator << (ostream &output, 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 << "请输入一个复数(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,c3;cin >> c1;cin >> c2;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;system("pause");return 0;}