2016-06-08 14 views
0

我的代碼:在C++公共傳承基地班的呼叫派生類的私有虛擬機能的研究

#include <iostream> 
using namespace std; 
class Base 
{ 
public: 
    void print() { doPrint();} 
private: 
    virtual void doPrint() {cout << "Base::doPrint" << endl;} 
}; 

class Derived : public Base 
{ 
private: 
    virtual void doPrint() {cout << "Derived::doPrint" << endl;} 
}; 

int main() 
{ 
    Derived *d = new Derived(); 
    Base* p = dynamic_cast<Base*>(d); 
    p->print(); 
    delete d; 
    return 0; 
} 

輸出爲Derived::doPrint,我不知道答案很好。爲什麼不是Base::doPrint?在公共繼承中,爲什麼Base類可以調用Derived類的私有虛函數?

+2

[找一本好書](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)並閱讀*多態*。 –

+0

也許這個問題的答案會幫助你。 http://stackoverflow.com/questions/4548145/low-level-details-of-inheritance-and-polymorphism – Arunmu

回答

0

虛擬會告訴它檢查要調用的函數。它仍然知道這是一個Derived。如果你還沒有把virtual這不起作用。閱讀更多關於多態的信息。

+0

謝謝,'虛擬'和'私人'是不相關的。我現在看得很清楚。 – cwfighter

0

即使在您編寫Base* p = dynamic_cast<Base*>(d);之後,p仍然是指向Derived實例的指針。

因此p->print();將調用Derived類的函數。

這就是如何在C++中使用多態性

1

在C++中,訪問檢查在靜態(編譯時間)類型的表達式的完成,但虛擬呼叫使用動態(運行時)的類型。

在你的例子中,*p有靜態類型Base和動態類型Derived

相關問題