MST

星途 面试题库

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

假设有一个`Vehicle`类作为基类,它具有`speed`(速度)和`direction`(方向)成员变量以及相应的访问函数。现在要派生出`Car`类和`Bicycle`类。`Car`类新增`fuelType`(燃料类型)成员变量,并重写一个`printInfo`函数来输出所有信息;`Bicycle`类新增`numGears`(档位数量)成员变量,同样重写`printInfo`函数。请用C++实现,要求考虑合适的构造函数、析构函数以及访问控制。给出完整的代码实现,包括类的定义、成员函数实现以及一个简单的测试主函数。
50.1万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
#include <iostream>
#include <string>

class Vehicle {
protected:
    double speed;
    std::string direction;
public:
    Vehicle(double s = 0, const std::string& d = "forward") : speed(s), direction(d) {}
    virtual ~Vehicle() {}
    double getSpeed() const { return speed; }
    std::string getDirection() const { return direction; }
    virtual void printInfo() const {
        std::cout << "Speed: " << speed << " Direction: " << direction << std::endl;
    }
};

class Car : public Vehicle {
private:
    std::string fuelType;
public:
    Car(double s, const std::string& d, const std::string& ft) : Vehicle(s, d), fuelType(ft) {}
    ~Car() override {}
    void printInfo() const override {
        std::cout << "Car - Speed: " << speed << " Direction: " << direction << " Fuel Type: " << fuelType << std::endl;
    }
};

class Bicycle : public Vehicle {
private:
    int numGears;
public:
    Bicycle(double s, const std::string& d, int ng) : Vehicle(s, d), numGears(ng) {}
    ~Bicycle() override {}
    void printInfo() const override {
        std::cout << "Bicycle - Speed: " << speed << " Direction: " << direction << " Number of Gears: " << numGears << std::endl;
    }
};

int main() {
    Vehicle* vehicle1 = new Car(60, "north", "gasoline");
    Vehicle* vehicle2 = new Bicycle(15, "east", 7);

    vehicle1->printInfo();
    vehicle2->printInfo();

    delete vehicle1;
    delete vehicle2;

    return 0;
}