問題描述
與受保護的繼承不同,C++ 私有繼承進入了主流 C++ 開發.但是,我仍然沒有找到它的好用途.
Unlike protected inheritance, C++ private inheritance found its way into mainstream C++ development. However, I still haven't found a good use for it.
你們什么時候使用它?
推薦答案
接受答案后的注意事項:這不是一個完整的答案.閱讀其他答案,例如此處(概念上)和這里(都是理論上的和實踐)如果你對這個問題感興趣.這只是可以通過私有繼承實現的奇特技巧.雖然很花哨這不是問題的答案.
Note after answer acceptance: This is NOT a complete answer. Read other answers like here (conceptually) and here (both theoretic and practic) if you are interested in the question. This is just a fancy trick that can be achieved with private inheritance. While it is fancy it is not the answer to the question.
除了 C++ 常見問題(鏈接在其他人的評論中)中顯示的私有繼承的基本用法之外,您還可以使用私有和虛擬繼承的組合來密封一個類(在 .NET 術語中)或制作一個 final 類(在 Java 術語中).這不是一個常見的用途,但無論如何我覺得它很有趣:
Besides the basic usage of just private inheritance shown in the C++ FAQ (linked in other's comments) you can use a combination of private and virtual inheritance to seal a class (in .NET terminology) or to make a class final (in Java terminology). This is not a common use, but anyway I found it interesting:
class ClassSealer {
private:
friend class Sealed;
ClassSealer() {}
};
class Sealed : private virtual ClassSealer
{
// ...
};
class FailsToDerive : public Sealed
{
// Cannot be instantiated
};
Sealed 可以實例化.它派生自ClassSealer,可以像朋友一樣直接調用私有構造函數.
Sealed can be instantiated. It derives from ClassSealer and can call the private constructor directly as it is a friend.
FailsToDerive 不會編譯,因為它必須直接調用 ClassSealer 構造函數(虛擬繼承要求),但不能編譯,因為它在 Sealed 類,在這種情況下 FailsToDerive 不是 ClassSealer 的朋友.
FailsToDerive won't compile as it must call the ClassSealer constructor directly (virtual inheritance requirement), but it cannot as it is private in the Sealed class and in this case FailsToDerive is not a friend of ClassSealer.
編輯
評論中提到,在使用 CRTP 時,這無法通用.C++11 標準通過提供不同的語法來幫助模板參數消除該限制:
It was mentioned in the comments that this could not be made generic at the time using CRTP. The C++11 standard removes that limitation by providing a different syntax to befriend template arguments:
template <typename T>
class Seal {
friend T; // not: friend class T!!!
Seal() {}
};
class Sealed : private virtual Seal<Sealed> // ...
當然這都是沒有實際意義的,因為 C++11 提供了一個 final
上下文關鍵字正是為了這個目的:
Of course this is all moot, since C++11 provides a final
contextual keyword for exactly this purpose:
class Sealed final // ...
這篇關于我什么時候應該使用 C++ 私有繼承?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!