有没有办法指定或断言子类必须重新实现特定的非抽象虚方法?

时间:2015-06-30 13:02:10

标签: c++ inheritance

这就是我的意思。我有一个类层次结构:

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

1 个答案:

答案 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.