2015-07-10 68 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派生類的成員,您必須使用虛擬函數,

  • ,在編譯時就判定其功能將是執行的,這就是爲什麼它被稱爲

運行時多態性或動態綁定