2015-07-10 66 views
-5

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

https://en.wikipedia.org/wiki/Virtual_function – JimmyB

+0

[Virtual functions](http://stackoverflow.com/questions/6520394/virtual-functions) – JimmyB

+0

Derived * Dptr = new Derived( ); Dptr =&D;' - >内存泄漏。 – JimmyB

回答

0

当我们想使用类型指针,基类来访问派生类的成员时,使用虚函数。

  • 时会使用

Bptr = d;

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

  • ,在编译时就判定其功能将是执行的,这就是为什么它被称为

运行时多态性或动态绑定