使用VC6打开考生文件夹下的工程test7_1,此工程包含一个源程序文件test7_1.cpp,但该程序运行有问题,请改正程序中的错误,使程序的输出结果如下:
Constructor1
Constructor1
Constructor1
Destructor
Constructor2
Destructor
x=0
x=5
Destructor
Destructor
源程序文件test1_1.cpp清单如下:
#include<iostream.h>
class B
int X;
public:
B()X=0;cout<<"Constructorl"<<endl;
B(int i)x=i;cout<<"Constructor2"<<endl;
~B()cout<<"Destructor"<<endl;
/**********found*********/
~B(int i)cout<<i<<"be Destructor"<<endl;
void print()cout<<"x="<<x<<endl;
;
void main()
B *ptr;
ptr=new B[2];
/**********found*********/
ptr[0]=B(0);
ptr[1]=B(5);
/**********found********/
for(int i=0; i<2;)
ptr[i].print();
delete []ptr;
参考答案:
(1)错误:~B(int i){cout<<"be Destructor"<<endl;}
正确:应将其删除
(2)错误:ptr[0]=B(0);
正确:ptr[0]=B();
(3)错误:for(int=0;i<2;)
正确:for(int i=0;i<2;i++)
解析:
(1)主要考查考生对析构函数特性的掌握,析构函数不能带参数也不能重载,一个类中只能定义一个析构函数,因为析构函数在删除对象的时候被默认调用,如果含有多个析构函数则可能引起多次删除产生的意外错误;
(2)主要考查考生对构造函数与函数重载的掌握,由输出结果可知其应该调用不带参数的构造函数B();
(3)主要考查考生对for循环语句的使用,如果在for循环中不写第三个表达式就意味着该循环一直会进行下去,因为 i的值总是小于2(在for循环体中对i进行操作也可以)。