1
考慮下面的代碼:如何在基類中使用接口?
#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;
}
我需要使用接口ITimer A類,但該方法是在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
你正在使用哪種編譯器? – Saravanan
@Nawaz:'我需要在類A中使用接口ITimer,但是該方法在類B中實現。所以我繼承了A中的接口' – Jichao