请使用“答题”菜单或使用VC6打开考生文件夹proj2下的工程proj2,其中包含抽象类Shape的声明,以及在此基础上派生出的类Rectangle和Circle的声明,二者分别是计算面积的函数GetArea()和计算对象周长的函数GetPerim()。程序中位于每个//************found************下的语句行有错,请加以改正。改正后程序的输出应该是:
The area of the Circle is 78.5
The perimeter of the Circle is 31.4
The area of the Rectangle is 24
The perimeter of the Rectangle is 20
注意:只能在画线处填写适当的代码,不要改动程序中的其他内容,也不能删除或移动“//************found************”。
//源程序
#include<iostream>
using namespace std;
class Shape
public:
Shape()
~Shape()
//************found************
______float GetArea()=0;
//************found************
______float GetPerim()=0;
;
class Circle: public Shape
public:
Circle(float radius):itsRadius(radius)
~Circle()
float CetArea() return 3.14 *itsRadius *itsRadius;
float CetPerim()return 6.28 *itsRadius;
private:
float itsRadius:
;
class Rectangle: public Shape
public:
//************found************
Rectangle(float len, float width):______;
~Rectangle();
virtual float GetArea() return itsLength *itsWidth;
float GetPerim()return 2*itsLength+2*itsWidth;
virtual float GetLength() return itsLength;
virtual float GetWidth()return itsWidth;
private:
float itsWidth;
float itsLength;
;
int main()
//************found************
sp=new Circle(5);
cout<<"The area of the Circle is"<<sp->GetArea()<<endl;
cout<<"The perimeter of the Circle is"<<sp->GetPerim()<<endl;
delete sp;
sp=new Rectangle(4,6);
cout<<"The area of the Rectangle is"<<sp->GetArea()<<endl;
cout<<"The perimeter of the Rectangle is"<<sp->GetPerim()<<endl;
delete sp;
return 0:
参考答案:
A)virtual float GetArea()=0;
B)virtual float GetPerim()=0;
C)Rectangle(float len, float width):itsWidth(width),itsLength(len){};
D)Shape*sp;
解析:
1)纯虚函数的定义格式为:
virtual函数类型 函数名()=0;
在Rectangle类中,可看到GetArea是虚函数的重新定义,故可知在基类Shape中GetArea应该是被定义为纯虚函数。
2)根据float GetPerim()=0;可以推断是将GetPerim()定义为纯虚函数,所以将纯虚函数的定义补齐。
3)定义Rectangle的带参构造函数,在构成函数的数据成员初始化列表中,对itsWidth和itsLength进行分别赋值。因为在函数体部分没有对该数据成员进行赋值,所以在声明的头部应当进行赋值。格式如下:
类名::构造函数名([参数表])[:数据成员1(初始值1),数据成员2(初始值2),…]
4)定义指针后可用。