2010-02-28 39 views
1

我有一個tempated基類檢查和公開派生類childcheck。基類也有一個部分特殊化,但我從一般模板類繼承了子類檢查類(而不是從類檢查的局部特化)。當我打電話從派生類的初始化列表基類的構造函數,編譯器會發出錯誤,現在如果我刪除類檢查的部分特則編譯器會發出任何錯誤,所以這裏是代碼
模板和繼承問題!

#include<iostream.h> 
template<class t> 
class check 
{ 
t object; 
public: 
check(t element); 
}; 
template<class t> 
check<t>::check<t>(t element) 
{ 
cout<<"base class constructor"<<endl; 
} 



//partial specialization 
template<class t> 
class check<t*> 
{ 
int objectsize; 
t* object; 
public: 
check(t*,int); 
t* getelement()const; 
~check(); 
}; 
template<typename t> 
check<t*>::check<t*>(t* ptr,int size) 
{ 
cout<<"\n partial specialization constructor"; 
} 




//derived class 
template< class t> 
class childcheck:public check<t> 
{ 
t chobject; 
public: 
childcheck(t); 
t getobject()const; 
}; 
template<class t> 
childcheck<t>::childcheck(t element):check<t>(element+1) 
{ 
cout<<"derived class constructro"<<endl; 
} 



//and this is the main function 
main() 
{ 
int* ptr; 
int x=2; 
ptr=&x; 
childcheck<int*> object(ptr); 
system("pause"); 
} 

回答

3

check<t*>::check(t*,int); c'tor有兩個參數,但是您從派生類初始化列表中調用它作爲check<t>(element+1)(使用t == int *,因此部分特化是實例化的)。

+0

是你的權利,非常感謝你 –

0

更一般地說,您面臨着專業化的共同問題。

當您編寫模板類的專業化時,通常您必須注意它的接口並確保它與您專門設計的模板類的接口相匹配,否則會產生令人討厭的驚喜。

當然有些情況下,專業化的目標是提供不同的行爲,而某些操作不再有意義,但是由於不能再處理任何實例像任何其他模板,必須寫的,其界面有所不同專業化的特殊情況......

而你剛剛發現這是沒有樂趣;)