第九周项目一:Complex类
2013-05-07 08:20
471 查看
/* * Copyright (c) 2012, 烟台大学计算机学院 * All rights reserved. * 作 者:李巧丽 * 完成日期:2013 年 5 月 7 日 * 版 本 号:v1.0 * 输入描述: * 问题描述:定义Complex类中的<<和>>运算符的重载,实现输入和输出, 改造原程序中对运算结果显示方式,使程序读起来更自然。 * 程序输出: * 问题分析: * 算法设计:略 */ #include <iostream> #include <Cstring> 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 istream& operator>>(istream &cin,Complex&c); friend ostream& operator<<(ostream &cout,Complex&c); private: double real; double imag; }; Complex operator+(Complex &c1,Complex &c2) { Complex c; c.real=c1.real+c2.real; c.imag=c1.imag+c2.imag; return c; } Complex operator-(Complex &c1,Complex &c2) { Complex c; c.real=c1.real-c2.real; c.imag=c1.imag-c2.imag; return c; } Complex operator*(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/(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; } istream & operator>>(istream&cin,Complex&c) { cout<<"请输入复数的实部与虚部"<<endl; cin>>c.real>>c.imag; return cin; } ostream & operator<<(ostream &cout,Complex&c) { cout<<"("; cout<<c.real; cout<<","<<c.imag<<"i)"<<endl; return cout; } int main( ) { Complex c1,c2,c3; cin>>c1>>c2; cout<<c1<<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; }
运行结果:
相关文章推荐
- 第九周上机任务项目1-Complex类
- 第九周--项目1-Complex类
- 第九周项目1:Complex类
- 第九周【项目1】在第8周项1的基础上(1)再定义一目运算符 -,-c相当于0-c(2)定义Complex类中的<<和>>运算符的重载,实现输入和输出,改造原程序中对运算结果显示方式,使程序读起来更自然
- 第九周-任务1-Complex类中运算符的重载
- 第九周项目3-稀疏矩阵的三元组表示的实现(1)
- 第九周项目三C/C++利用二叉树遍历思想解决问题
- C++第九周任务-项目三(分数类)
- 第九周项目2-对称矩阵压缩存储的实现与应用(2)
- 第九周 项目四--我的向量类
- 第九周 项目4 广义表应用
- 第九周 项目一 猴子选大王
- 第九周 项目3 稀疏矩阵的三元组表示的实现及应用(矩阵相加)
- C++程序设计-第九周分支结构程序设计上机实践项目
- 第九周 项目2-对称矩阵压缩存储的实现和应用(2)
- 第九周-项目3-稀疏矩阵的三元组表示的实现及应用
- 第九周--项目三--稀疏矩阵的三元组表示的实现及应用(2)
- 第九周项目 4 类族的设计(2)
- 第九周 项目二-对称矩形压缩存储的实现与应用(二)
- 第九周项目3—稀疏矩阵的三元组表示的实现及应用(1)