欢迎来到天天文库
浏览记录
ID:55926159
大小:83.50 KB
页数:32页
时间:2020-06-15
《C++上机考试题,上机练习,东南大学C++上机实验.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、/*定义一个复数类,通过重载运算符:=、+=、-=、+、-、*、/、==、!=,直接实现两个复数之间的各种运算。编写一个完整的程序(包括测试各运算符的程序部分)。*/#include"stdio.h"//标准输入输出头文件#include"iostream.h"classComplex{floatReal,Image;public:Complex(floatr=0,floati=0){Real=r;Image=i;};floatGetR(){returnReal;}floatGetI(){returnImage;}//后面主函数要直接调用私有成员数据v
2、oidshow(){cout<<"Real="<3、erator!=(Complex&);intoperator==(Complex&);//返回真假};ComplexComplex::operator+(Complex&c)//此时的函数名变为Complex::operator{Complext;//在函数体内可以定义新的类,并把这个临时的类返回,同样用打点来访问t.Real=Real+c.Real;t.Image=Image+c.Image;returnt;}voidComplex::operator+=(Complex&c){Real=Real+c.Real;Image=Image+c.Image4、;}ComplexComplex::operator-(Complex&c){Complext;t.Real=Real-c.Real;t.Image=Image-c.Image;returnt;}voidComplex::operator-=(Complex&c){Real=Real-c.Real;Image=Image-c.Image;}ComplexComplex::operator*(Complex&c){Complext;t.Real=Real*c.Real-Image*c.Image;t.Image=Real*c.Image+Image*c.5、Real;returnt;}ComplexComplex::operator/(Complex&c){Complext;t.Real=Real*c.Real+Image*c.Image;t.Image=-Real*c.Image-Image*c.Real;floatval=c.Real*c.Real+c.Image*c.Image;t.Real=t.Real/val;t.Image=t.Image/val;returnt;}voidComplex::operator=(Complex&c){Real=c.Real;Image=c.Image;}intC6、omplex::operator!=(Complex&c){intres;//函数体内定义临时变量res=(c.Real!=Real)&&(c.Image!=Image);returnres;}intComplex::operator==(Complex&c){intres;res=(c.Real==Real)&&(c.Image==Image);returnres;}voidmain(){Complexa(3,4),b(6,8),c,d;c=a;//赋值=c.show();d=a+b;//+d.show();c=b-a;//-c.show();c=b7、;c+=a;//+=c.show();d=b;d-=a;//-=d.show();//c=a;d=a;cout<8、时的类返回,同样用打点来访问/*四、下标运算符[]通常用于取数组中某个元素,可以实现数组下标越
3、erator!=(Complex&);intoperator==(Complex&);//返回真假};ComplexComplex::operator+(Complex&c)//此时的函数名变为Complex::operator{Complext;//在函数体内可以定义新的类,并把这个临时的类返回,同样用打点来访问t.Real=Real+c.Real;t.Image=Image+c.Image;returnt;}voidComplex::operator+=(Complex&c){Real=Real+c.Real;Image=Image+c.Image
4、;}ComplexComplex::operator-(Complex&c){Complext;t.Real=Real-c.Real;t.Image=Image-c.Image;returnt;}voidComplex::operator-=(Complex&c){Real=Real-c.Real;Image=Image-c.Image;}ComplexComplex::operator*(Complex&c){Complext;t.Real=Real*c.Real-Image*c.Image;t.Image=Real*c.Image+Image*c.
5、Real;returnt;}ComplexComplex::operator/(Complex&c){Complext;t.Real=Real*c.Real+Image*c.Image;t.Image=-Real*c.Image-Image*c.Real;floatval=c.Real*c.Real+c.Image*c.Image;t.Real=t.Real/val;t.Image=t.Image/val;returnt;}voidComplex::operator=(Complex&c){Real=c.Real;Image=c.Image;}intC
6、omplex::operator!=(Complex&c){intres;//函数体内定义临时变量res=(c.Real!=Real)&&(c.Image!=Image);returnres;}intComplex::operator==(Complex&c){intres;res=(c.Real==Real)&&(c.Image==Image);returnres;}voidmain(){Complexa(3,4),b(6,8),c,d;c=a;//赋值=c.show();d=a+b;//+d.show();c=b-a;//-c.show();c=b
7、;c+=a;//+=c.show();d=b;d-=a;//-=d.show();//c=a;d=a;cout<8、时的类返回,同样用打点来访问/*四、下标运算符[]通常用于取数组中某个元素,可以实现数组下标越
8、时的类返回,同样用打点来访问/*四、下标运算符[]通常用于取数组中某个元素,可以实现数组下标越
此文档下载收益归作者所有