![](/img/trans.png)
[英]common function in base and derived calling base when called through another base function using a derived object?
[英]How to warn (or error) when calling a function that is only implemented in base but not derived?
我真的不確定如何簡要地給這個問題命名。
情況:
Base
作為接口,它指定了我們擁有的所有特性(成員函數)。 還有多個派生類可以實現功能的子集。 這些函數是虛函數。Derived
中是否存在 function。要求:
也許解決方案(不完美):
實現Base
中的每個功能並在內部拋出錯誤。 在Derived
中使用using
並將 function 放在私有字段中。 缺點。 如果有新功能,我們需要將其添加到每個 class。如果我們忘記這樣做,則沒有警告。
在Base
中使用純虛函數,並在每個Derived
中為每個特性實現它們。 缺點: Derived
不需要的那些功能的許多實現(和代碼),並且實現都是相同的 - 拋出錯誤。
更新:
對於 11.:通過“很多實現”,我做了一個例子: https://godbolt.org/z/sW8eKjbhx 。
您可以將此 function 標記為純虛擬。 然后它必須在派生類中被覆蓋。 它仍然可以有身體。
class Base {
public:
virtual void f() = 0;
};
void Base::f() {
// ...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.