[英]How a friend function of a base class is calling the overridden virtual function of derived class even though they are private ?(C++)
[英]C++ Why I can invoke private virtual function of base class from a drived class?
赫伯·薩特(Herb Sutter)的著名文章Virtuality指出:
准則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;
}
預先感謝您的回復
那是因為您要調用drived
的private_base_func
版本,當然可以在drived
訪問它。 您不能調用的函數是base
的版本:
drived()
{
base::private_base_func(); // this line will not compile
}
private_base_func(); // this line should not compile
怎么會這樣? private_base_func
是一個private
的功能drived
和行內drived
,所以它是完全沒有調用它。 請注意,這不同於:
drived()
{
base b;
b.private_base_func(); // this line does not compile
}
無論如何,這不是本文的目的。 本文的重點是在基類中定義了兩個不同的接口。 一種是公共界面,它提供基礎用戶所需的操作。 另一個是虛擬函數集,它定義了擴展提供給基類的操作。 通過分離兩個接口,您可以將用戶與提供程序分離,並獲得靈活性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.