如何在基类中使用接口
How to use interface in a base-class?
考虑以下代码:
#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++)
相关文章:
- 如何在基类中定义静态接口,并确保该接口必须在派生类中实现
- C++:继承自基类和具有公共基接口的多个接口
- 如何在基类中实现子类迭代器的统一接口?
- 使用基类指针 - cpp 的适当声明设计接口
- 您如何将界面称为班级及其基类之间的接口
- 如何私下从基类的导数继承,但实现基类的公共接口?
- 在派生类接口中隐藏基类的特定函数
- 我应该为接口还是抽象基类编程?该短语到底是什么意思
- 基类c++的子类的通用设计接口
- 在C++中实现类似接口的纯抽象基类的最佳实践
- 覆盖基类的虚函数,这些基类不共享公共接口
- c++:通过基类接口构造派生对象
- 为什么C++不允许基类实现派生类的继承接口?
- 如何在基类中使用接口
- 通过抽象模板基类接口指针访问派生类方法,而无需在接口中显式类型
- C++:向基类接口添加一个方法
- 如何通过多态基类接口使用模板化的子类
- 编译时检查基类是否为"接口"
- 如何使用基类的接口
- 基类方法的接口