MST

星途 面试题库

面试题:C++派生新类步骤的代码实现 - 中等难度

请用C++代码实现从一个基础类`Shape`派生出`Circle`类,`Shape`类有一个虚函数`draw`用于绘制图形,`Circle`类需要重写`draw`函数以绘制圆形。同时,`Circle`类有一个表示半径的成员变量,在构造函数中初始化。请给出完整的代码框架。
37.9万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>

class Shape {
public:
    virtual void draw() const {
        std::cout << "Drawing a shape." << std::endl;
    }
};

class Circle : public Shape {
private:
    double radius;
public:
    Circle(double r) : radius(r) {}

    void draw() const override {
        std::cout << "Drawing a circle with radius " << radius << std::endl;
    }
};