目录
一、背景
在C++中,多态性(Polymorphism)是一种允许对象通过相同的接口进行不同操作的能力。多态性主要通过继承和虚函数来实现。
二、相关概念
2.1、继承
继承(Inheritance)是面向对象编程中的一个基本概念,它允许一个类(派生类)继承另一个类(基类)的属性和方法。通过继承,派生类可以重用基类的代码,并且可以根据需要添加新的功能或重写现有功能。
2.2、虚函数
虚函数(Virtual Function)是实现运行时多态性的关键。虚函数允许派生类重写基类中的方法,并在运行时根据对象的实际类型调用相应的方法。
2.3、基本语法
在基类中,使用 virtual
关键字声明虚函数。例如:
class Base {
public:
virtual void show() {
std::cout << "Base class show function called." << std::endl;
}
};
在派生类中,可以重写这个虚函数:
class Derived : public Base {
public:
void show() override {
std::cout << "Derived class show function called." << std::endl;
}
};
2.3、使用虚函数表
每个包含虚函数的类有一个虚函数表(VTable),这个表包含指向虚函数的指针。在运行时,通过对象的实际类型的虚函数表来调用相应的函数。
#include <iostream>
class Base {
public:
virtual void show() {
std::cout << "Base class show function called." <&