所有的虚函数都需要在派生类中实现吗?
这似乎是一个简单的问题,但我在其他任何地方都找不到答案.
This may seem like a simple question, but I can't find the answer anywhere else.
假设我有以下内容:
class Abstract {
public:
virtual void foo() = 0;
virtual void bar();
}
class Derived : Abstract {
public:
virtual void foo();
}
Derived 类不实现 bar() 函数可以吗?如果不是我的所有派生类都需要 bar() 函数,但有些需要,该怎么办.抽象基类的所有虚函数都需要在派生类中实现,还是只需要在纯虚函数中实现?谢谢
Is it ok that class Derived does not implement the bar() function? What if not ALL of my derived classes need the bar() function, but some do. Do all of the virtual functions of an abstract base class need to be implemented in the derived classes, or just the ones that are pure virtual? Thanks
推荐答案
派生类不必自己实现所有虚函数.他们只需要实现 pure 的那些.1 这意味着问题中的 Derived
类是正确的.它继承其祖先类Abstract
的bar
实现.(这假设 Abstract::bar
在某处实现.问题中的代码声明了该方法,但没有定义它.您可以将其定义为 Trenki's answer 显示,或者您可以单独定义它.)
Derived classes do not have to implement all virtual functions themselves. They only need to implement the pure ones.1 That means the Derived
class in the question is correct. It inherits the bar
implementation from its ancestor class, Abstract
. (This assumes that Abstract::bar
is implemented somewhere. The code in the question declares the method, but doesn't define it. You can define it inline as Trenki's answer shows, or you can define it separately.)
1 即便如此,仅当派生类要实例化时.如果派生类没有直接实例化,而只是作为更多派生类的基类存在,那么负责实现所有纯虚方法的是那些那些类.层次结构中的中间"类允许保留一些未实现的纯虚拟方法,就像基类一样.如果中间"类确实实现了一个纯虚方法,那么它的后代将继承该实现,因此他们不必自己重新实现它.
1 And even then, only if the derived class is going to be instantiated. If a derived class is not instantiated directly, but only exists as a base class of more derived classes, then it's those classes that are responsible for having all their pure virtual methods implemented. The "middle" class in the hierarchy is allowed to leave some pure virtual methods unimplemented, just like the base class. If the "middle" class does implement a pure virtual method, then its descendants will inherit that implementation, so they don't have to re-implement it themselves.
相关文章