欢迎来到天天文库
浏览记录
ID:35972163
大小:173.00 KB
页数:9页
时间:2019-04-29
《实验报告实验4.doc》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验四类定义与类构造实验一、实验目的1.掌握面向对象的基本概念,类的定义方法;2.掌握类成员的访问权限及访问类成员的方法;3.掌握运算符重载为成员函数和友元函数的方法;4.理解友元函数和友元类;5.理解静态数据成员。二、实验内容编程:建立一个分数类。分数类的数据成员包括分子和分母,成员函数包括显示、输入、约分、通分、比较、加、减、乘、除、求相反数。要求:(1)完成所有成员函数,并用上述主函数验证是否达到设计要求,理解为何将约分函数reduction()和通分函数makeCommond(fraction)设计为分数类的私有成员函数而非公有成员;(
2、2)自行编写约分函数reduction()和通分函数makeCommond(fraction),可自己设计,也可参考其它资料。程序:#include#includeusingnamespacestd;classfraction{intabove;//分子intbelow;//分母voidreduction();//约分voidmakeCommond(fraction&);//通分public:fraction(inta=0,intb=1){//构造函数above=a;below=b;}fractionadd(f
3、raction);//两分数相加fractionsub(fraction);//本分数减去实参分数fractionmul(fraction);//两分数相乘fractiondiv(fraction);//本分数除以实参分数fractionreciprocal();//求倒数boolequal(fraction);//等于运算boolgreaterThan(fraction);//大于运算boollessThan(fraction);//小于运算voiddisplay();//显示分数voidinput();//输入分数};voidfractio
4、n::reduction(){//约分先求最大公约数inta,b,temp;if(below<0){above=-above;below=-below;}a=abs(above);b=abs(below);while(a%b){//欧几里德法求最大公约数temp=a;a=b;b=temp%b;}above/=b;below/=b;}voidfraction::makeCommond(fraction&b){inttemp;reduction();b.reduction();above*=b.below;b.above*=below;temp=b
5、elow*b.below;below=b.below=temp;}fractionfraction::add(fractionb){fractiontemp;makeCommond(b);//通分temp.above=above+b.above;temp.below=below;temp.reduction();//约分returntemp;}fractionfraction::sub(fractionb){fractiontemp;makeCommond(b);//通分temp.above=above-b.above;temp.below=b
6、elow;temp.reduction();//约分returntemp;}fractionfraction::mul(fractionb){fractiontemp;temp.above=above*b.above;temp.below=below*b.below;temp.reduction();//约分returntemp;}fractionfraction::div(fractionb){fractiontemp;if(b.above==0){cout<<"零不能作除数!"<7、*b.below;temp.below=below*b.above;temp.reduction();//约分returntemp;}fractionfraction::reciprocal(){fractiontemp;temp.above=below;temp.below=above;temp.reduction();//约分returntemp;}boolfraction::equal(fractionb){makeCommond(b);//通分return(above==b.above);}boolfraction::greaterTh8、an(fractionb){makeCommond(b);//通分return(above>b.above);}boolfraction::lessT
7、*b.below;temp.below=below*b.above;temp.reduction();//约分returntemp;}fractionfraction::reciprocal(){fractiontemp;temp.above=below;temp.below=above;temp.reduction();//约分returntemp;}boolfraction::equal(fractionb){makeCommond(b);//通分return(above==b.above);}boolfraction::greaterTh
8、an(fractionb){makeCommond(b);//通分return(above>b.above);}boolfraction::lessT
此文档下载收益归作者所有