[英]Private overriden virtual functions in derived class
如果這些在基礎 class 中是公共的,那么從基礎 class 覆蓋的虛擬成員函數有什么意義?
struct base {
virtual void a();
};
struct derived : base {
// ...
private:
void a() override;
};
查看您的設計,我發現無法直接調用derived::a
,而只能通過base
接口調用。
有什么意義嗎? 考慮一下,一旦我們有一個derived
實例,我們總是可以向上轉換到它的基礎,所以給定
derived d;
雖然da()
不會編譯,但我們總是可以這樣做
base & b = d;
b.a(); //which actually calls derived::a
換句話說: derived::a
畢竟不是那么私密,我不鼓勵這種設計,這可能會讓用戶感到困惑。
如果derived
中的 private 成員在base
中也是私有的,情況就會發生變化:這一次很明顯,它們不能在base
或derived
之外直接調用。
假設我們有幾個函數,並希望根據作為參數傳遞給第三個函數的值有條件地調用它們:
struct base
{
void dosomething(bool x)
{
if(x)
{
do_this();
}
else
{
do_that();
}
}
private:
virtual void do_this(){}
virtual void do_that(){}
};
因此派生的 class 可能類似於:
struct derived : base
{
private:
void do_this() override { }
void do_that() override { }
};
並且沒有其他 class 可以調用它們,除非它擴展了base
本身:
derived d;
d.dosomething(true); //will call do_this() in derived
d.dosomething(false); //will call do_that() in derived
d.do_that() //won't compile
是的,如果您將基礎 class 繼承為私有。 否則,它更像是一種奇怪的顯式限制——用戶必須進行顯式轉換才能使用 function——通常不建議這樣做,因為很少有人能夠理解作者的意圖。
如果您想限制基本 class 中的某些功能,請創建一個私有/受保護的 inheritance 並通過using
關鍵字聲明您希望在派生的 class 中保護/公開哪些基本方法。
如果您被迫對實現 class 進行兩階段構造(即具有init()
方法以及或代替必須調用的構造函數(我知道,但有原因),那么這會讓您停止在將實例指針作為接口指針傳回之前,直接在實例指針上調用任何 /other/ 方法。Go 加倍努力,將 inheritance 設為私有,並讓您的一個公共初始化 ZC1C425268E68384F1AB5074C17
另一個原因是您不需要/需要/寫public:
在最終實現 class 聲明中,所以默認情況下一切都是私有的。 但是為什么你會這樣做並使用 struct 而不是 class 我不知道。 也許這是由於風格戰爭而在某個時候從 class 轉換而來的?
與非虛擬方法相同的推理適用:如果只有 class 本身應該將其稱為私有。
考慮模板方法模式:
struct base {
void foo() { a() ; b(); }
virtual void a() = 0;
virtual void b() = 0;
};
struct derived : base {
private:
void a() override {}
void b() override {}
};
int main()
{
derived().foo();
}
也許a
和b
應該受到protected
,但無論如何, derived
可以改變可訪問性,並且它需要一些文檔,以便derived
知道它應該如何實現a
和b
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.