#include <iostream>
#include <memory>
// 定义抽象类Animal
class Animal {
public:
// 纯虚函数makeSound
virtual void makeSound() const = 0;
// 析构函数声明为虚函数,确保正确的析构
virtual ~Animal() = default;
};
// 派生类Dog
class Dog : public Animal {
public:
void makeSound() const override {
std::cout << "汪汪" << std::endl;
}
};
// 派生类Cat
class Cat : public Animal {
public:
void makeSound() const override {
std::cout << "喵喵" << std::endl;
}
};
int main() {
// 使用std::unique_ptr管理对象内存,避免内存泄漏
std::unique_ptr<Animal[]> animals(new Animal*[2] {
new Dog(),
new Cat()
});
// 通过循环调用makeSound函数实现多态
for (size_t i = 0; i < 2; ++i) {
animals[i]->makeSound();
}
// 这里std::unique_ptr会自动释放内存,无需手动delete
return 0;
}
- 抽象类
Animal
:定义了纯虚函数 makeSound()
,用于派生类实现不同的声音行为,并将析构函数声明为虚函数,以确保在释放派生类对象时调用正确的析构函数。
- 派生类
Dog
和 Cat
:分别实现了 makeSound()
函数,发出“汪汪”和“喵喵”的声音。
- 主函数:
- 使用
std::unique_ptr
管理 Animal
指针数组,从而避免内存泄漏。
- 通过循环遍历数组,调用
makeSound()
函数,实现多态行为。当 std::unique_ptr
超出作用域时,会自动释放其所管理的对象内存。