欢迎来到天天文库
浏览记录
ID:40646049
大小:28.00 KB
页数:4页
时间:2019-08-05
《编写复数类Complex》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、编写复数类Complex。要求:1)类里面需要重载运算符函数,包括:复数加法+(二元),复数减法-(二元),复数求负-(一元)和复数赋值=(二元)。2)类里面有输出该复数的函数print。3)类的声明写在Complex.h中,类的实现写在Complex.cpp中。4)写出以上两个文件即可,无需客户代码。5)在思考以上问题时,可参考如下客户代码(假设类已编写好):#include"complex.h"#includeintmain(){COMPLEXc1(1,2);//定义一个值为1+2i的复数c1COMPLEXc2(2);//定义一个值为2的复数
2、c2COMPLEXc3(c1);//用拷贝构造函数创建一个值同c1的新复数c3.print();//打印c3的值c1=c1+c2+c3;//将c1加上c2再加上c3赋值给c1c2=-c3;//c2等于c3求负c3=c2-c1;//c3等于c2减去c1c3.print();//再打印运算后c3的值return0;}#include"iostream.h"classcomplex{public:complex(){real=imag=0.0;}complex(doubler){real=r;imag=0.0;}complex(doubler,doublei){real=r;
3、imag=i;}complex(complex&cp){real=cp.real;imag=cp.imag;}friendcomplexoperator+(constcomplex&c1,constcomplex&c2);friendcomplexoperator-(constcomplex&c1,constcomplex&c2);inlinecomplexoperator+=(constcomplex&c);inlinecomplexoperator-=(constcomplex&c);voidprint();private:doublereal,imag;};com
4、plexoperator+(constcomplex&c1,constcomplex&c2){returncomplex(c1.real+c2.real,c1.imag+c2.imag);}complexoperator-(constcomplex&c1,constcomplex&c2){returncomplex(c1.real-c2.real,c1.imag-c2.imag);}inlinecomplexcomplex::operator+=(constcomplex&c){return(real+c.real,imag+c.imag);}inlinecomplex
5、complex::operator-=(constcomplex&c){return(real-c.real,imag-c.imag);}voidcomplex::print(){if(imag<0){cout<6、印c3的值c1=c1+c2+c3;//将c1加上c2再加上c3赋值给c1c2-=c3;//c2等于c3求负c3=c2-c1;//c3等于c2减去c1c3.print();//再打印运算后c3的值return0;}
6、印c3的值c1=c1+c2+c3;//将c1加上c2再加上c3赋值给c1c2-=c3;//c2等于c3求负c3=c2-c1;//c3等于c2减去c1c3.print();//再打印运算后c3的值return0;}
此文档下载收益归作者所有