2013-09-26 27 views
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類中實現

感謝。

+2

爲什麼'A'繼承'ITimer'? – Nawaz

+0

你正在使用哪種編譯器? – Saravanan

+0

@Nawaz:'我需要在類A中使用接口ITimer,但是該方法在類B中實現。所以我繼承了A中的接口' – Jichao

回答

4

繼承是所有邪惡的基礎階級。

A也不BITimer小號

一個甚至沒有實現純虛擬的,所以它不能被實例化。因此,從A繼承使得C摘要也(不能實例化)。

你不想在這裏使用繼承。見


在這種情況下,可怕的鑽石的死亡層次可以通過添加virtual固定:

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

查看它Live on IdeOne。不過,我不推薦這樣做。考慮修復設計。

又見Diamond inheritance (C++)

+0

+1爲「考慮修復設計」。 – rightfold