c++如何实现虚函数的动态绑定
时间: 2024-06-14 12:04:36 浏览: 119
C++通过使用虚函数和虚函数表来实现动态绑定。当一个类中声明了虚函数时,编译器会为该类创建一个虚函数表。虚函数表是一个存储了虚函数地址的数组,每个类只有一个虚函数表。当一个对象被创建时,会在对象的内存布局中添加一个指向虚函数表的指针,这个指针被称为虚函数表指针。
当通过基类指针或引用调用虚函数时,编译器会根据对象的实际类型(而不是指针或引用的类型)来确定调用哪个虚函数。编译器会根据对象的虚函数表指针找到对应的虚函数表,然后根据函数在虚函数表中的索引找到要调用的虚函数的地址,最后通过该地址调用虚函数。
以下是一个示例代码,演示了C++如何实现虚函数的动态绑定:
```cpp
#include <iostream>
class Base {
public:
virtual void print() {
std::cout << "Base::print()" << std::endl;
}
};
class Derived : public Base {
public:
void print() override {
std::cout << "Derived::print()" << std::endl;
}
};
int main() {
Base* basePtr = new Derived();
basePtr->print(); // 输出:Derived::print()
delete basePtr;
return 0;
}
```
在上面的代码中,基类`Base`中声明了一个虚函数`print()`,派生类`Derived`重写了这个虚函数。在`main()`函数中,通过基类指针`basePtr`指向派生类对象`Derived`,然后调用`basePtr->print()`。由于`print()`是一个虚函数,编译器会根据`basePtr`指向的对象的实际类型来确定调用哪个虚函数,最终输出`Derived::print()`。
阅读全文
相关推荐















