简体   繁体   English

如何在基类中使用接口?

[英]How to use interface in a base-class?

considering following code: 考虑以下代码:

#include <stdio.h>
struct ITimer {
    virtual void createTimer() = 0;
};
class A : public ITimer
{
    public:
        void showA() {
            printf("showA\n");
            createTimer();
        }
};

class B : public ITimer
{
    public:
        void showB() {
            printf("showB\n");
        }
        void createTimer() {
            printf("createTimer");
        }
};

class C: public A, public B
{
    public:
        void test() {
            showA();
            showB();
        }
};

int main()
{
    C c;
    c.test();
    return 0;
}

I need to use interface ITimer in class A, but the method is implemented in class B. So I inherited the interface in A, but the compiler is not happy with it: 我需要在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'

How could I use the interface in baseclass A while its method is implemented in class B. 如何在基类A中使用该接口,而其方法在B类中实现。

Thanks. 谢谢。

Inheritance is the base-class of all evil. 继承是所有邪恶的基础阶级。

A nor B are ITimer s AB 都是 ITimer

A doesn't even implement the pure virtual, so it cannot be instantiated. A甚至没有实现纯虚拟,因此无法实例化。 Therefore, inheriting from A makes C abstract too (cannot be instantiated). 因此,继承自A使C 抽象 (无法实例化)。

You don't want to use inheritance here. 你不想在这里使用继承。 See 看到


In this case, the dreaded diamond-of-death hierarchy could be fixed by adding virtual : 在这种情况下,可以通过添加virtual来修复可怕的死亡钻石层次结构

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

See it Live on IdeOne . 在IdeOne上观看直播 I don't recommend this, though. 不过我不建议这样做。 Consider fixing the design. 考虑修复设计。

See also Diamond inheritance (C++) 另请参阅Diamond继承(C ++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM