香草薩特的名篇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;
}
謝謝進步爲您迴應