Dotcpp  /  试卷列表  /  C++  /  题目 7753

请使用“答题”菜单或使用VC6菜单打开考生文件夹pro

请使用“答题”菜单或使用VC6菜单打开考生文件夹proj2下的工程 proj2,其中包含抽象类Shape的声明,以及在此基础上派生出的类 Rectangle和Circle的声明,两者都有计算对象面积的函数GetArea()和 计算对象周长的函数GetPerim()。

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 GetArea() { return 3.14 * itsRadius * itsRadius; }
    float GetPerim () { 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;
}
答案
第1空:virtual
第2空:virtual
第3空:itsLength(len),itsWidth(width) / itsWidth(width),itsLength(len)
第4空:Shape *sp;
解析

由于第1、2两处后面的代码为“float GetArea()=0”及“float  GetPerim()=0”这两个成员函数必为纯虚函数,在C++中,定义虚拟函数

要使用“virtual”关键字,故第1、2两处应填“virtual”。

第3处的作用是利用构造函数的形参初始化类成员变量itswidth、itsLength;故第3空应填“itsWidth(width),itsLength(len)”或其等效形式;

第4处由“sp=new Circle(5);”及“sp=new Rectangle(4,6);”已知sp为一指向Circle及Rectangle共同基类的指针,即sp为shape型指针,第4空为“Shape *sp;”。


题目信息

题号:7753
题型:填空题
知识点:C++
难度:普通