我想實現模板專業化。我delcared模板和類:模板專業化與類
template <class T>
class Person{
public:
Person(char one, T two){
this -> prv = one;
this -> druh = two;
}
void explain();
private:
char prv;
T druh;
};
,並宣佈其吸氣劑
template <class T>
void Person<T>::explain(){
cout << "Druh isnt char" << endl;
}
現在,如果我創建的對象與不是char其它數據類型,它會indeeed輸出「Druh心不是CHAR」如
Person <int> obj('a',5);
obj1.explain(); // "Druh isnt char"
我想使用專業化,所以當第二個參數是字符時它會說"Druh is char"
我嘗試了使用:
/*********模板專業化***********/
template<>
class Person<char>{
public:
Person(char one, char two){
this-> prv = one;
this-> druh = two;
}
void explain();
};
和定義解釋再次方法
void Person<char>::explain(){
cout << "Druh is a char " << endl;
}
但我得到這個錯誤
「類人」沒有名爲「PRV」成員|
這是怎麼發生的?是否需要首先聲明Person類的私有變量?不是templat<>
對編譯器說,我不使用模板規範創建另一個對象?
類'人'不包含一個叫做'prv'成員。 –
Nard
'應該從班級人員的第一次申報中獲得私人變量嗎?不是。你爲什麼認爲應該這樣做? – cpplearner
然後使用模板專門化的要點是什麼?爲什麼不只是定義另一個班級。 – user3706129