- 南yi
-
22. 下面程序三次调用同一函数 sum ,在横线处填上适当内容,使输出结果为:
S=2
S=5
S=9
程序如下:
#include<iostream.h>
void sum(int i)
{
static int s;
_s+=2+i_________;
cout<< 〃 S= 〃 <<s<<endl;
}
void main (void)
{
int i;
for (i=0;_i<3; i++_______)
sum(i);
}
23. 在下面程序横线处填上适当的内容,使该程序输出结果为:
Creating B
end of B
end of A
程序如下:
#include<iostream.h>
class A
{
public:
A(){}
____~A()__________{cout<< “ end of A “ <<endl;}
};
class B:public A
{
public:
B(){__cout<<”creating B”<<endl;______}
~ B(){cout<< “ end of B “ <<endl;}
};
void main()
{
A*pa=new B;
delete pa ;
}
21. 在下面程序段横线处填上适当的内容。
class A{
_int *a;_______
int n;
public:
A(int nn=0):n(nn){
if(n==0)a=0;
else a=new int 〔 n 〕 ;
}
__~A(){delete [] a;}_____// 定义析构函数,释放动态数组空间
};
三、改错题
17. 此类定义有一处错误,请指出错误并改正。
class ABC{
int a;
public:
ABC(int aa)a(aa){} //更正为ABC(int aa):a(aa)
};
18. 指出下面程序中的错误,并说明出错原因。
#include<iostream.h>
class ConstFun{
public:
void ConstFun(){} //错误,构造函数没有返回值,去掉void
const int f5()const{return 5;}
int Obj() {return 45;}
int val;
int f8();
};
int ConstFun::f8(){return val;}
void main()
{
const ConstFun s;
int i=s.f5();
cout<< 〃 Value= 〃 <<i<endl;
}
19. 指出下面程序中的错误,并说明错误原因。
#include<iostream.h>
class A{
public:void fun(){cout<< 〃 a.fun 〃 <<endl;}
};
class B{
public:void fun(){cout<< 〃 b.fun 〃 <<endl;}
void gun(){cout<< 〃 b.gun 〃 <<endl;}
};
class C:public A,public B{
private:int b;
public:void gun(){cout << 〃 c.gun<< 〃 endl;}
};
void main(){
c obj;
obj.fun(); //错误obj.fun存在二义性,四调用objec.A::fun();还是objec.B::fun();
obj.gun();
}
20. 指出下面程序段中的错误,并说明出错原因。
class Location {
int X,Y;
protected:
int zeroX,zeroY;
int SetZero(int zeroX,int zeroY){X=zeroX;Y=zeroY;}
private:
int length,height;
public:
float radius;
void init(int initX,int initY){length=initX;height=initY;}
int GetX(){return X;}
int GetY(){return Y;}
};
int main(){
Location retangleA={25,20,3,5,6,7,3}; //类不能这样初始化,必须调用构造函数来初始化
return 0;
}
- 小教板
-
22 (1) s=s+i+2;
22 (2) i<3;i++
23 (1) virtual ~A()
23 (2) cout << "Creating B" << endl;
21 (1) int *a;
21 (2) ~A() { if(A!=NULL) delete [] a; }
17 aa没有初始化
18 (1) 构造函数不能有返回值
18 (2) 最后一句cout中应该为<<endl,少写个“<”
19 多态的基函数不能重名
20 没有构造函数