这就是我的意思。我有一个类层次结构:
class A {
virtual int f() = 0;
};
class B : public A {
int f() override {return 5;}
void doSpecificStuff() {}
}
B
是一个自给自足的类,可以单独使用。但它也有许多后代:
class C : public B {
int f() override {return 171;}
}
在子类化f
时,有没有办法确保我不会忘记重新实施B
?
答案 0 :(得分:5)
This solution is inspired by @dyp's comment:
You could split the two responsibilities of B
, namely "provides B
-style implementation" and "can be instantiated."
class B_for_implementation : public A
{
void doSpecificStuff();
};
class B_for_objects final : public B_for_implementation
{
int f() override {return 5;}
};
class C final : public B_for_implementation
{
int f() override {return 171;}
};
Self-contained objects would be created from B_for_objects
, while other classes would derive from B_for_implementation
.