欢迎来到天天文库
浏览记录
ID:6358824
大小:47.50 KB
页数:12页
时间:2018-01-11
《c++ 上机实验答案 类的定义与应用》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、实验2类的定义与应用1、实验目的和要求:掌握类定义的方法,理解类类型,实例的含义,体会面向对象程序设计中数据隐藏的概念。理解构造函数和析构函数的作用和运行时间,掌握拷贝构造函数的作用。并熟练掌握复杂对象类型的运用。2、实验内容:(1)定义一个时间类Time,它能提供由时、分、秒组成的时间。要求能够修改时间和打印出时间。#includeusingnamespacestd;classTime{public:voiddisplayTime();voidsetTime();private:inthour;intminute;intsecond;};voidTime::disp
2、layTime(){cout<>hour>>minute>>second;}(2)编写一个计数器类,定义一个私有数据成员,通过两个成员函数,分别使其完成加1和减1操作。用构造函数数据成员初始化为0,输出函数可以输出数据成员的值。#includeusingnamespacestd;classcounter{public:voidfunctionP();voidfunctionM();voidsetNum();voidprint();pr
3、ivate:intcNum;};voidcounter::functionP(){cNum++;}voidcounter::functionM(){cNum--;}voidcounter::setNum(){cNum=0;}voidcounter::print(){cout<<"counter="<usingnamesp
4、acestd;classTime{public:voiddisplayTime();Time();Time(intHour,intMinute,intSecond);~Time();voidsetHour(inth);voidsetMinute(intm);voidsetSecond(ints);voidsetTime(inthou,intmin,intsec);voidtick();private:inthour,minute,second;};Time::Time(intHour,intMinute,intSecond){hour=Hour;minute=Minute;second=
5、Second;}Time::~Time(){cout<<"destructing"<6、lse{second=0;minute++;}}else{second++;}}#includeusingnamespacestd;classRational{public:Rational(intnn,intmm);//构造函数voidR_add(Rational&A);//加voidR_sub(Rational&A);//减voidR_mul(Rational&A);//乘voidR_div(Rational&A);//除voidprint();//以简分数形式显示,注意约分private:voidsimple();//约分intm;//分母intn;//分子};7、Rational::Rational(intnn,intmm){n=nn;m=mm;}voidRational::R_add(Rational&A){n=A.m*n+A.n*m;m=A.m*m;simple();}voidRational::R_sub(Rational&A){n=A.m*n-A.n*m;m=A.m*m;simple();}voidRational::R_mul(Rational&A){n*=A.n;m*=A.m;s
6、lse{second=0;minute++;}}else{second++;}}#includeusingnamespacestd;classRational{public:Rational(intnn,intmm);//构造函数voidR_add(Rational&A);//加voidR_sub(Rational&A);//减voidR_mul(Rational&A);//乘voidR_div(Rational&A);//除voidprint();//以简分数形式显示,注意约分private:voidsimple();//约分intm;//分母intn;//分子};
7、Rational::Rational(intnn,intmm){n=nn;m=mm;}voidRational::R_add(Rational&A){n=A.m*n+A.n*m;m=A.m*m;simple();}voidRational::R_sub(Rational&A){n=A.m*n-A.n*m;m=A.m*m;simple();}voidRational::R_mul(Rational&A){n*=A.n;m*=A.m;s
此文档下载收益归作者所有