【问题标题】:How to use interface in a base-class?如何在基类中使用接口?
【发布时间】:2013-09-26 07:19:56
【问题描述】:

考虑以下代码:

#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;
}

我需要在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会继承ITimer
  • 你使用的是哪个编译器?
  • @Nawaz: I need to use interface ITimer in class A, but the method is implemented in class B. So I inherited the interface in A,
  • @Saravanan: gcc 和 msvc...
  • 继承是万恶之源。

标签: c++ design-patterns interface


【解决方案1】:

继承是万恶之源。

A 也不是 B ITimers

A 甚至没有实现纯虚,所以它不能被实例化。因此,从A 继承也使得C abstract (不能被实例化)。

您不想在这里使用继承。见


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

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

查看 Live on IdeOne。不过我不推荐这个。考虑修复设计。

另见Diamond inheritance (C++)

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2023-04-09
    • 2019-08-25
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2016-10-27
    • 2010-09-30
    • 2016-04-14
    相关资源
    最近更新 更多