在这个例子中,我们将定义一个基类 Vehicle,它包含所有交通工具共有的基本属性和方法。然后,我们将派生两个子类:Car 和 Bike,它们继承了 Vehicle 类的特性,并添加了各自特有的属性和方法。
基类 Vehicle
#include <iostream>
#include <string>
// 基类 Vehicle
class Vehicle {
protected:
std::string brand; // 交通工具的品牌
int year; // 交通工具的制造年份
public:
// 构造函数
Vehicle(const std::string& brand, int year) : brand(brand), year(year) {}
// 展示交通工具的基本信息
virtual void displayInfo() const {
std::cout << "Brand: " << brand << ", Year: " << year << std::endl;
}
// 虚析构函数,确保子类析构时能正确调用析构函数
virtual ~Vehicle() {}
};
派生类 Car
// 派生类 Car
class Car : public Vehicle {
private:
int seats; // 汽车的座位数
public:
// 构造函数,初始化基类部分和派生类特有的部分
Car(const std::string& brand, int year, int seats) : Vehicle(brand, year), seats(seats) {}
// 重写 displayInfo 方法,以展示汽车特有的信息
void displayInfo() const override {
Vehicle::displayInfo(); // 调用基类的 displayInfo 方法展示基本信息
std::cout << "Seats: " << seats << std::endl;
}
};
派生类 Bike
// 派生类 Bike
class Bike : public Vehicle {
private:
bool hasGear; // 自行车是否有变速器
public:
// 构造函数,初始化基类部分和派生类特有的部分
Bike(const std::string& brand, int year, bool hasGear) : Vehicle(brand, year), hasGear(hasGear) {}
// 重写 displayInfo 方法,以展示自行车特有的信息
void displayInfo() const override {
Vehicle::displayInfo(); // 调用基类的 displayInfo 方法展示基本信息
std::cout << "Has Gear: " << (hasGear ? "Yes" : "No") << std::endl;
}
};
主函数示例
int main() {
Car myCar("Toyota", 2020, 5);
Bike myBike("Giant", 2019, true);
// 使用指针数组来存储不同类型的 Vehicle 指针
Vehicle* vehicles[] = {&myCar, &myBike};
// 遍历并展示每个交通工具的信息
for (auto& vehicle : vehicles) {
vehicle->displayInfo(); // 多态调用,根据对象类型调用相应的 displayInfo 方法
std::cout << std::endl;
}
return 0;
}
在这个例子中,
Car
和 Bike
类通过继承 Vehicle
类重用了交通工具的基本特性,如品牌(brand
)和制造年份(year
),同时也通过扩展特有的属性(如汽车的座位数 seats
和自行车是否有变速器 hasGear
)来表现它们自己的特点。这样的设计不仅减少了代码重复,还提高了代码的可维护性和扩展性。
使用继承的优势
- 代码重用:继承允许子类重用父类的代码,这意味着可以通过编写更少的代码来实现功能。
- 可扩展性:如果需要添加新的交通工具类型,可以简单地通过继承
Vehicle
类来创建新的子类,无需修改现有类。 - 多态:如上例所示,通过将子类对象以
Vehicle
类型的指针或引用存储,可以在运行时确定调用哪个类的displayInfo
方法,这提高了程序的灵活性。
注意事项
- 虚析构函数:基类
Vehicle
中的析构函数被声明为虚函数(virtual ~Vehicle() {}
),这是因为当通过基类指针删除派生类对象时,确保调用正确的析构函数,避免内存泄漏。 - 重写方法:派生类中的
displayInfo
方法被标记为override
,这表明该方法重写了基类中的虚方法。这对于代码的清晰性和减少错误非常有帮助。
通过继承和多态性,C++ 允许开发者在不同层次的类之间共享和扩展代码。这个简单的例子展示了如何通过继承来重用代码,并通过覆盖基类中的方法来为每个派生类添加特定的行为。继承是面向对象编程中一个强大的工具,能够帮助开发者构建灵活、可维护的代码结构。