第九章综合练习题参考答案Word文件下载.doc
《第九章综合练习题参考答案Word文件下载.doc》由会员分享,可在线阅读,更多相关《第九章综合练习题参考答案Word文件下载.doc(5页珍藏版)》请在冰点文库上搜索。
};
Samples;
int*p=&
s.m;
A.s.p=5;
B.s->
p=5;
C.*p=5;
D.*s.p=5
3.下列定义中,Sample是一个类,(B)是定义指向对象数组的指针p。
A.Sample*p[5] B.Sample(*p)[5] C.(Sample*)p[5] D.Sample*p[]
4.this指针是分配给被调用的成员函数的指针,*this表示(D)。
A.成员函数的形参 B.对象所调用的成员函数 C.成员函数种的数据成员 D.调用成员函数的对象
5.下列有关类和对象的说法中,正确的是(C)
A.类和对象没有区别
B.要为类和对象分配存储空间
C.对象是类的实例,为对象分配存储空间而不为类分配存储空间
D.类是对象的实例,为类分配存储空间而不为对象分配存储空间
二、阅读程序题(40分)
1.执行以下程序后,其输出结果是(102+202i)
classComplex{
floatReal,Image;
Complex*Add();
voidPrint()
{ cout<
<
Real<
'
+'
Image<
i'
endl;
}
Complex*Complex:
Add()
{
Real++;
Image++;
returnthis;
}
voidmain(void)
{ Complexc1={100,200};
c1.Add()->
Add();
c1.Print();
2.执行以下程序后,输出的第一行是(fun1:
7),第二行是(fun2:
15)。
classA{
intx;
voidfun1(intj){x+=j;
cout<
"
fun1:
x<
voidfun2(intj){x+=j;
fun2:
{ Ac1={2},c2={5};
void(A:
*pf)(int);
pf=A:
fun1;
(c1.*pf)(5);
fun2;
(c2.*pf)(10);
三、完善程序题(20分)
下列程序中类T的定义包含两个私有成员数据p1和p2,共有成员函数voidInit(char*s1,char*s2)的功能是将s1和s2所指向的字符串分别送给p1和p2,成员函数voidCopyT(T&
t)的功能是将当前对象(指调用该成员函数的对象)的私有成员p1和p2复制给对象t的对应成员变量,成员函数voidFreeT()的功能是释放p1和p2的内存空间。
请完善下面的程序。
string.h>
classT{
char*p1,*p2;
voidInit(char*s1,char*s2);
{cout<
p1="
p1<
endl<
p2="
p2<
voidCopyT(T&
t)
{t.Init(p1,p2);
voidFreeT(void)
{
if(p1)delete[]p1;
if(p2)delete[]p2;
voidT:
Init(char*s1,char*s2)
p1=newchar[strlen(s1)+1];
p2=newchar[strlen(s2)+1];
strcpy(p1,s1);
strcpy(p2,s2);
Tt1,t2;
t1.Init("
abc"
"
def"
);
t1.CopyT(t2);
t2.Print();
t1.FreeT();
t2.FreeT();
四、程序设计题(20分)
下列是用链表结构实现简单的栈的程序,请补充类stack定义中的Put(intitem)和Get()两个成员函数,这两个成员函数的功能分别是将数据入栈和出栈,数据的进出栈按先进后出的原则。
structNode
{ inta;
Node*next;
classstack
{
Node*head;
voidPut(intitem);
//将数据item插入到栈中
intGet();
//从栈中取一个数据
voidPrint();
//输出栈中的数据
voidDestroy();
//释放链表的存储空间
voidstack:
Put(intitem)
{ Node*p=head,*pend;
if(head==NULL){
p=newNode;
p->
a=item;
next=NULL;
head=p;
else{
while(p->
next!
=NULL)p=p->
next;
pend=p;
pend->
next=p;
intstack:
Get()
{ Node*p1=head,*p2=head;
intitem;
if(head){
while(p2->
=NULL){
p1=p2;
p2=p2->
}
item=p2->
a;
p1->
deletep2;
returnitem;
elsereturn0;
Print()
{ Node*p=head;
while(p){
cout<
p->
a<
\t'
;
p=p->
cout<
elsecout<
空栈,没有数据项!
\n"
Destroy()
Node*p=head,*p1;
if(head)
p1=p;
deletep1;
stackst={0};
st.Put(10);
st.Put(12);
st.Put(14);
cout<
现在栈中的数据项是:
st.Print();
现在出栈的数据是:
st.Get()<
st.Destroy();