如何在基类中使用接口

How to use interface in a base-class?

本文关键字:接口 基类      更新时间:2023-10-16

考虑以下代码:

#include <stdio.h>
struct ITimer {
    virtual void createTimer() = 0;
};
class A : public ITimer
{
    public:
        void showA() {
            printf("showAn");
            createTimer();
        }
};
class B : public ITimer
{
    public:
        void showB() {
            printf("showBn");
        }
        void createTimer() {
            printf("createTimer");
        }
};
class C: public A, public B
{
    public:
        void test() {
            showA();
            showB();
        }
};
int main()
{
    C c;
    c.test();
    return 0;
}

我需要在 A 类中使用接口 ITimer,但该方法是在 B 类中实现的。所以我继承了 A 中的接口,但编译器对此不满意:

test.cc
test.cc(38) : error C2259: 'C' : cannot instantiate abstract class
        due to following members:
        'void ITimer::createTimer(void)' : is abstract
        test.cc(5) : see declaration of 'ITimer::createTimer'

当基类 A 的方法在类 B 中实现时,我如何使用该接口。

谢谢。

继承是万恶的基础类。

A也不是B ITimer

A 甚至没有实现纯虚拟,因此无法实例化。因此,从A继承也会使C抽象(无法实例化)。

您不想在此处使用继承。看

  • 利斯科夫替代原则("is-a"规则)

在这种情况下,可以通过添加virtual来修复可怕的死亡钻石层次结构

class A : public virtual ITimer
//...
class B : public virtual ITimer

IdeOne上观看直播。不过,我不建议这样做。考虑修复设计。

参见 钻石传承 (C++)