21xrx.com
2024-09-20 01:13:57 Friday
登录
文章检索 我的文章 写文章
C++期末试题:程序阅读题
2023-07-04 15:59:56 深夜i     --     --
C++ 期末试题 程序阅读 编程知识 考试复习

C++期末试题中,有一道程序阅读题,需要对一段给定的程序代码进行阅读、理解和分析,并回答相关的问题。

以下是给定的程序代码:


#include <iostream>

using namespace std;

class Shape {

public:

  virtual int getArea() return 0;

};

class Circle : public Shape {

public:

  Circle(int r) : radius(r) {}

  int getArea() { return 3.14 * radius * radius; }

private:

  int radius;

};

class Rectangle : public Shape {

public:

  Rectangle(int w, int h) : width(w), height(h) {}

  int getArea() { return width * height; }

private:

  int width;

  int height;

};

int main() {

  Shape* pShape = new Circle(5);

  cout << "Area of Circle: " << pShape->getArea() << endl;

  pShape = new Rectangle(4, 6);

  cout << "Area of Rectangle: " << pShape->getArea() << endl;

  return 0;

}

这个程序定义了一个 Shape 类,以及两个派生类 Circle 和 Rectangle。 Shape 类里面定义了一个虚函数 getArea(),派生类 Circle 和 Rectangle 分别实现了这个函数,分别计算了圆的面积和矩形的面积。在主函数中,分别创建了一个 Circle 对象和一个 Rectangle 对象,并输出它们的面积。

那么,下面就是这道程序阅读题需要回答的问题:

问题1:程序里面的虚函数有什么作用?

答:虚函数的作用是使派生类可以重写基类的函数,实现多态。

问题2:Circle 和 Rectangle 类是如何继承 Shape 类的?

答:Circle 和 Rectangle 类分别使用关键字 public 继承 Shape 类。

问题3:程序中的虚函数是如何实现多态的?

答:程序中通过指针 pShape 来调用函数 getArea(),通过虚函数的机制,实现多态性调用,可以让程序在运行时解析对象的类型,并根据对象的具体类型来调用相应的虚函数。在这里, pShape 指向 Circle 对象和 Rectangle 对象时, getArea() 方法都被正确地调用了。

问题4:为什么要使用虚函数?

答:在多态机制中,通过调用虚函数,可以将一个对象按照其实际类型进行调用,使程序具有更好的灵活性和可扩展性。此外,虚函数也可以保证类的继承层次结构中的合理性和正确性,防止因为多个类继承同一个基类时导致的命名冲突。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复