这似乎是一个简单的问题,但我在其他地方找不到答案。
假设我有以下内容:
class Abstract {
public:
virtual void foo() = 0;
virtual void bar();
}
class Derived : Abstract {
public:
virtual void foo();
}
Derived 类不实现 bar() 函数可以吗?
如果不是所有派生类都需要 bar() 函数,但有些派生类需要,该怎么办?
抽象基类的所有虚函数是否都需要在派生类中实现,还是只需要纯虚函数?
谢谢
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 https://stackoverflow.com/a/8931719/33732 shows, or you can define it separately.)
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.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)