GESP 六级 · GESP 202406 C++ 六级 第 3 题

选择题 · 答案 A · 考点:函数

← 整套速查表 GESP 六级 全部真题

题目

运行下列代码,屏幕上输出( )。

#include <iostream>
using namespace std;

class shape {
protected:
    int width, height;
public:
    shape(int a = 0, int b = 0) {
        width = a;
        height = b;
    }
    virtual int area() {
        cout << "parent class area: " << endl;
        return 0;
    }
};

class rectangle: public shape {
public:
    rectangle(int a = 0, int b = 0) : shape(a, b) { }

    int area() {
        cout << "rectangle area: ";
        return (width * height);
    }
};

class triangle: public shape {
public:
    triangle(int a = 0, int b = 0) : shape(a, b) { }

    int area() {
        cout << "triangle area: ";
        return (width * height / 2);
    }
};

int main() {
    shape *pshape;
    rectangle rec(10, 7);
    triangle tri(10, 5);

    pshape = &rec;
    pshape->area();

    pshape = &tri;
    pshape->area();
    return 0;
}
答案:A

考点

函数

解题思维

C++类:构造函数(对象创建时调用)、析构函数(对象销毁时调用)、虚函数(实现多态)。构造函数不能为虚。

常见错误

构造函数不能是虚函数(虚表在构造函数完成后才建立)。析构函数可以且通常应该为虚函数(防止内存泄漏)。

详细解析(节选)

【考点】C++虚函数|多态|面向对象

1. 🎯 考纲定位

本题锁定在GESP 六级《面向对象编程》模块的"虚函数与多态"核心考点。命题人专门在此处设题,就是要卡住大量考生对"虚函数才是多态的前提"这一机制的理解断层——六级学生常误以为只要继承就能多态,却忽视"virtual"关键字的决定性作用。

同考点真题

在 OI伴学 里做这道题
登录后可计时作答、查看完整六段式解析,并按你的错题自动生成同类练习。
去刷题先做一次 AI 学情诊断