虚函数的使用场景
虚函数在C++中的使用场景通常涉及到以下几种情况:
1.实现多态:当需要在基类中通过指针或引用调用派生类中重写的函数时,虚函数是必不可少的。这允许基类指针或引用在运行时能够动态地调用当前对象的实际派生类中的函数实现。
2.设计可扩展的框架:在设计一个可扩展的框架时,可以通过虚函数提供接口,允许用户在不修改原有代码的基础上通过继承和重写来扩展功能。
3.处理继承体系中的共享行为:当基类中的某些行为适用于所有派生类,但派生类可能需要提供特定的实现时,虚函数可以在基类中定义,并在需要时在派生类中被重写。
4.提供接口规范:纯虚函数可以强制要求派生类实现某些功能,这使得基类可以作为一个抽象类,提供一个清晰的接口规范,确保所有派生类至少实现这些必需的功能。
代码示例
以下是一个使用虚函数实现多态的代码示例:
#include
// 基类定义虚函数
class Animal {
public:
virtual void speak() const {
std::cout << “Animal makes a sound.” << std::endl;
}
virtual ~Animal() {} // 虚析构函数以确保正确销毁派生类对象
};
// 派生类重写虚函数
class Dog : public Animal {
public:
void speak() const override {
std::cout << “Dog barks.” << std::endl;
}
};
class Cat : public Animal {
public:
void speak() const override {
std::cout << “Cat meows.” << std::endl;
}
};
int main() {
Animal* myPets[2];
myPets[0] = new Dog();
myPets[1] = new Cat();
for (int i = 0; i < 2; ++i) {myPets[i]->speak(); // 通过基类指针调用正确的重写函数
}delete myPets[0];
delete myPets[1];return 0;
}
在这个示例中,Animal 类定义了一个虚函数 speak(),Dog 和 Cat 类都继承了 Animal 并重写了 speak() 函数。在 main 函数中,通过 Animal 类型的指针数组来管理不同类型的动物对象,并调用 speak() 函数。由于 speak() 是虚函数,因此会根据指针实际指向的对象类型来调用正确的重写版本.
参考:
[1]:https://blog.csdn.net/qingzhuyuxian/article/details/95613896
[2]:https://blog.csdn.net/2401_83733103/article/details/142313535
[3]:https://blog.csdn.net/wcc243588569/article/details/141597029
[4]:https://blog.csdn.net/wkd_007/article/details/140316339
[5]:https://blog.csdn.net/qq_42864343/article/details/134488942
[6]:https://baike.baidu.com/item/virtual/3371630
[7]:https://zhuanlan.zhihu.com/p/616684277
[8]:https://zhuanlan.zhihu.com/p/419510666