虚函数的整体思想是什么?

时间:2015-07-10 13:59:59

标签: c++ function polymorphism virtual

在代码中,我能够成功地将派生类指针指向基类对象,并且我还能够设置和获取基类私有成员的值。如果这没有给出任何问题那么虚拟函数的需求和运行时多态性/后期绑定/ vtable bla bla bal !!!的整个混乱是什么!!!

#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;
}

1 个答案:

答案 0 :(得分:0)

在我们想要使用类型的指针,基类访问派生类的成员的情况下使用虚函数。

  • 何时使用
  

Bptr =安培; d;

您无法访问Derived类的成员,但从Base类继承的成员除外。 如果要使用与Bptr相同的指针访问Derived类的成员,则必须使用虚函数,

  • 并且在编译时决定将执行哪个功能,这就是为什么它被称为
  

运行时多态或动态绑定

相关问题