2013-04-03 37 views
1

香草薩特的名篇Virtuality,規定如下:C++爲什麼我可以從一個掘進類中調用基類的私有虛擬函數?

方針#2:不想做虛函數私有

這很容易。這使派生類重寫功能 定製行爲,而且不會進一步使他們調用由派生類直接暴露虛擬 功能(如同職能只是保護 將是可能的)

在下面的代碼,所述private_base_func()是在基類聲明私有虛擬函數,並稱之爲在掘進類的構造,奇怪的是,這個代碼編譯細並將其從掘進類,調用基類的私有虛擬函數與上述說法相抵觸。這讓我非常困惑。

class base 
{ 
public: 

    base() {} 
    virtual ~base(){} 

private: 
    virtual void private_base_func() 
    { 
     std::cout << "Base Class invoke" << std::endl; 
    } 

}; 


class drived : public base 
{ 
public: 
    drived() 
    { 
     private_base_func(); // this line should not compile 
    } 

private: 
    // Overriding base class virtual function 
    void private_base_func() 
    { 
     std::cout << "Drived class invoke" << std::endl; 
    } 
}; 

int main() 
{ 
    base* ptr = new drived(); 
    return 0; 
} 

謝謝進步爲您迴應

回答

8

那是因爲你調用drived的版本private_base_func,這當然是內drived訪問的。你不能調用該函數是base的版本:

drived() 
{ 
    base::private_base_func(); // this line will not compile 
} 
1
private_base_func(); // this line should not compile 

怎麼會這樣? private_base_funcdrived一個private功能和行內drived,所以它是完全沒有調用它。請注意,這不同於:

drived() 
{ 
    base b; 
    b.private_base_func(); // this line does not compile 
} 

無論如何,這不是文章的內容。文章的要點是在基類中定義了兩個不同的接口。一個是公共接口,提供基地用戶需要的操作。另一組是虛擬函數,它定義了你的擴展爲你的基類提供的操作。通過分離兩個界面,您可以將用戶與提供商分離並獲得靈活性。

相關問題