虚函数的整个思想是什么

What is the whole idea of virtual function?

本文关键字:是什么 函数      更新时间:2023-10-16

在代码中,我能够成功地将派生类指针指向基类对象,并且我还能够设置和获取基类私有成员的值。如果这没有给任何问题,那么什么是虚函数的需要,以及围绕运行时多态性/延迟绑定/虚表之类的混乱!!

#include <iostream>
using namespace std;
class Base
{
    int a;
public:
    Base(int x=0):a(x){}
    void setValueForMember(int p)
    {
        a=p;
    }
    void showValueOfMember(){cout<<endl<<a<<endl;}
};
class Derived:public Base
{
    int b;
public:
    Derived(){}
    Derived(int y):b(y){}
    void setValueForMember(int q)
    {
        b=q;
    }
    void showValueOfMember(){cout<<endl<<b<<endl;}
};
int main()
{
    Derived D;
    D.setValueForMember(10);
    Derived *Dptr = new Derived();
    Dptr = &D;
    Dptr->showValueOfMember();
    Base B;
    Dptr = (Derived*)&B;
    Dptr->setValueForMember(20);
    Dptr->showValueOfMember();
    return 0;
}

虚函数用于希望使用基类类型的指针访问派生类的成员的情况。

  • 何时使用

Bptr =研发;

将不能访问派生类的成员,除了从基类继承的成员。如果希望使用与Bptr相同的指针访问派生类的成员,则必须使用虚函数

  • 在编译时决定执行哪个函数,这就是为什么它被称为

运行时多态性或动态绑定