【问题标题】:What is the whole idea of virtual function?虚函数的整体思想是什么?
【发布时间】:2015-09-29 07:38:05
【问题描述】:

在代码中,我能够成功地将派生类指针指向基类对象,并且我还能够设置和获取基类私有成员的值。如果这没有给出任何问题,那么需要什么虚函数以及围绕运行时多态性/后期绑定/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;
}

【问题讨论】:

标签: c++ function polymorphism virtual


【解决方案1】:

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

  • 什么时候使用

Bptr=&D;

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

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

运行时多态性或动态绑定

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2019-08-06
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多