问题 填空题

使用VC6打开考生文件夹下的工程test42_1,此工程包含一个源程序文件test42_1.cpp,但该程序运行有问题,请改正函数中的错误,使该程序的输出结果为: rect area: 12 rectb area: 30 源程序文件test42_1.cpp清单如下: #include <iostream.h> class CRectangle {/***************** found *****************/int *width, height; public: CRectangle (int,int); ~CRectangle (); int area (void) {return (*width * *height);} }; CRectangle::CRectangle (int a, int b) {width = new int;height = new int;/***************** found *****************/width = a;*height = b; } CRectangle::~CRectangle () {delete width;delete height; } /***************** found *****************/ void main () {CRectangle rect (3,4), rectb (5,6);cout << "rect area: "<< rect.area() << endl;cout << "rectb area: "<< rectb.area() << endl;return 0; }

答案

参考答案:

解析:(1) 错误:int*width,height; 正确:int*width,*height; (2) 错误:width=a; 正确:*width=a; (3) 错误:void main() 正确;int main() (1)根据后面类中构造函数的定义可以看出只有定义成指针的变量才能动态申请空间,所以本题的错误在于没有把变量 height定义成指针类型; (2)变量width是指针类型的变量,直接给它赋值相当于让它指向一个新的地址,而要改变它指向的变量的值,应该使用取内容符号“*”: (3)根据主函数最后的返回值情况,可知该主函数是需要定义成带返回值的函数,本题的错误在于,把主函数定义成了void,改成int即可,考生一定要注意函数定义的返回值和最后实际的返回情况是否一一对应。

单项选择题
单项选择题