C++面向对象程序设计习题集.doc
C++面向对象程序设计习题集
编程题:用面向对象的程序设计方法编制如下程序。
1.
设计一个Bank类,实现银行某账号的资金往来账管理,包括建账号、存入、取出等。Bank类包括私有数据成员top(当前指针)、date(日期)、money(金额)、rest(余额)和sum(累计余额)。另有一个构造函数和3个成员函数bankinO(处理存入账)、bankout()(处理取出账)和disp()(出明细账)。
【知识点】:2.22.3
【参考分】:25分
【难易度】:B
【答案】:
#includeiostream.h
#includeiomanip.h
#includestring.h
constintMax=100;
classBank
{
inttop;
chardate[Max][10];//日期
intmoney[Max];//金额
intrest[Max];//余额
staticintsum;//累计余额
public:
Bank(){top=0;}
voidbankin(chard[],intm)
{
strcpy(date[top],d);
money[top]=m;
sum=sum+m;
rest[top]=sum;
top++;
}
voidbankout(chard[],intm)
{
strcpy(date[top],d);
money[top]=-m;//取出数用负数表示
sum=sum-m;
rest[top]=sum;
top++;
}
voiddisp()
{
inti;
cout日期存入取出余额endl;
for(i=0;itop;i++)
{
coutsetw(10)date[i];
if(money[i]0)
coutsetw(6)-money[i];
else
coutsetw(6)money[i];
coutsetw(6)rest[i]endl;
};
intBank::sum=0;
voidmain()
{
Bankobj;
obj.bankin(2005.2.5.1000);
obj.bankin(2006.3.2,2000);
obj.bankout(2007.4.1,500);
obj.bankout(2007.10.5,800);
obj.disp();
}
2.
编写一个程序,已有假设干个学生数据,包括学号、姓名、成绩,要求输出这些学生数据并计算平均分。
【知识点】:2.22.3
【参考分】:20分
【难易度】:B
【答案】:
#includeiostream.h
#includeiomanip.h
#includestring.h
classStud
{
intno;
charname[10];
intdeg;
staticintsum;
staticintnum;
public:
Stud(intn,charna[],intd)
{
no=n;deg=d;
strcpy(name,na);
sum+=d;
num++;
}
staticdoubleavg()
{
returnsum/num;
}
voiddisp()
{
coutsetw(5)nOsetw(8)namesetw(6)degendl;
}
};
intStud::sum=0j
intStud::num=O;
voidmain()
{
Studs1(1,Li,89),s2(2,Chert,78),s3(3,zheng,94);
cout:学号姓名成绩endl;
s1.disp();
s2.disp();
s3.disp();
cout平均分=Stud::avg()endl;
}
3.
有10个单词存放在一维指针数组words中,编写一个程序,根据用户的输入找出所有与之从前向后匹配的单词和个数。
【知识点】:2.2
【参考分】:25分
【难易度】:B
【答案】:设计一个Word类,包含一个私有数据成员words、一个构造函数和一个公有成员函数look