所有虚拟函数是否需要在派生类中实现? [英] Do ALL virtual functions need to be implemented in derived classes?

查看:853
本文介绍了所有虚拟函数是否需要在派生类中实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能看起来像一个简单的问题,但我在其他任何地方找不到答案。

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

推荐答案

派生类必须实现虚函数本身。它们只需要实现 1 这意味着问题中的 Derived 类是正确的。它从其祖先类抽象继承 bar 实现。 (这假设 Abstract :: bar 是在某处实现的,问题中的代码声明了方法,但没有定义它,你可以将它定义为 Trenki的回答显示,或您可以单独定义。)

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.

这篇关于所有虚拟函数是否需要在派生类中实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆