c++面向对象程序设计实验2Word下载.docx
《c++面向对象程序设计实验2Word下载.docx》由会员分享,可在线阅读,更多相关《c++面向对象程序设计实验2Word下载.docx(15页珍藏版)》请在冰点文库上搜索。
cout<
<
data.a1<
endl;
data.a2<
}
2.分析以下程序的错误原因,给出修改方案使之能正确运行。
#include<
classAmplifier{
floatinvol,outvol;
public:
Amplifier(floatvin,floatvout)
{invol=vin;
outvol=vout;
floatgain();
Amplifier:
:
floatgain(){returnoutvol/invol;
}
{Amplifieramp(5.0,10.0);
cout<
"
\n\nThegainis=>
gain()<
3.定义盒子Box类,要求具有以下成员:
可设置盒子形状;
可计算盒子体积;
可计算盒子的表面积。
4.定义计数器类Counter。
要求具有以下成员:
计数器值;
可进行增值和减值计数;
可提供计数值。
5.编写一个程序计算两个给定的长方形的周长和面积。
6.编写一个程序,采用一个类求n!
并输出10!
的值。
7.编写一个程序,设计一个Cdate类,它应该满足下面的条件:
1)用这样的格式输出日期:
日-月-年;
2)输出在当前日期上加两天后的日期;
3)设置日期。
三、实验源程序、测试与结论
1.分析:
出错原因:
class成员的缺省访问权限时private,私有成员中能被类中的其他成员函数调用。
修改方案:
{
inta1,a2;
one(intx1=0,intx2=0)
{
a1=x1;
a2=x2;
voidshow()
a1<
a2<
onedata(2,3);
data.show();
测试数据截图:
2.
类外定义成员函数格式:
成员函数返回类型类名:
:
成员函数名(参数表);
成员函数的引用。
classAmplifier
invol=vin;
floatAmplifier:
gain()
{
returnoutvol/invol;
Amplifieramp(5.0,10.0);
amp.gain()<
3.
#include"
iostream"
cmath"
usingnamespacestd;
classBox
intl,w,h;
ints,v;
Box(inta,intb,intc)
l=a;
w=b;
h=c;
intarea()
returns=2*(l*w+w*h+h*l);
intvolume()
returnv=l*w*h;
Thearea:
area()<
Thevolume:
volume()<
inta,b,c;
Pleaseenterthelonghighwidth:
;
cin>
>
a>
b>
c;
BoxB1(a,b,c);
B1.show();
4.
classCounter
intnum;
Counter(intn)
{num=n;
voidincrease()
{num++;
voidreduction()
{num--;
{cout<
num<
inti,j;
Pleaseenteranumber:
i;
CounterC1(i);
\n1.Theoriginalnumber"
2.Theincreasenumber"
3.Thereductionnumber"
\nPleaseenteranumber:
j;
switch(j)
case1:
Thenumber:
C1.show();
break;
case2:
C1.increase();
case3:
C1.reduction();
5.
classrectangle
intl,w;
intc,s;
rectangle(inta,intb)
intgirth()
{returnc=2*(l+w);
{returns=l*w;
Thelength:
l<
Thewidth:
w<
Thegirth:
girth()<
\n"
rectangleR1(2,5),R2(3,6);
R1.show();
R2.show();
6.
classtest
intfactorial(intn)
if(n==0)
return1;
else
returnn*factorial(n-1);
testnum;
10!
num.factorial(10)<
7.
#include"
string"
classCdate
intyear;
intmonth;
intday;
Cdate(inty,intm,intd)
{
if((m>
=1&
&
m<
=12))
{
if(m==2)
{
if(!
(y%4))
{
if(d>
d<
=29)
{
year=y;
month=m;
day=d;
}
else
cout<
当前日期不合法!
return;
}
else
=28)
}
}
elseif(m==4||m==6||m==9||m==11)
if(d>
=30)
year=y;
month=m;
day=d;
else
cout<
return;
else
=31)
}
}
voidadd(intx)
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
{
if(day+2>
31)
{
month+=1;
day=2-(31-day);
if(month==13)
{
month-=12;
year+=1;
day+=2;
}
elseif(month==2)
if(day+2>
28)
month+=1;
if(year%4==0)
day=2-(29-day);
else
day=2-(28-day);
elseif(day+2>
30)
day=2-(30-day);
day+=2;
两天后日期(日-月-年):
day<
-"
month<
year<
今天日期为:
intyear,month,day;
按年,月,日的输入顺序设置当前日期:
year>
month>
day;
Cdatedate(year,month,day);
date.show();
date.add
(2);