2012-02-19 107 views
2

我有以下代碼:C++抽象類模板

template <typename T> 
class ListBase 
{ 
protected: 
    int _size; 
public: 
    ListBase() {_size=0;} 
    virtual ~ListBase() {} 
    bool isEmpty() {return (_size ==0);} 
    int getSize() {return _size;} 

    virtual bool insert(int index, const T &item) = 0; 
    virtual bool remove(int index) = 0; 
    virtual bool retrieve(int index, T &item) = 0; 
    virtual string toString() = 0; 
}; 

我的第二文件定義了一個子類:

#define MAXSIZE 50 
template <class T> 
class ListArray : public ListBase 
{//for now to keep things simple use int type only later upgrade to template 
private: 
    T arraydata[MAXSIZE]; 
public: 

    bool insert(int index,const T &item) 
    { 
     if(index >= MAXSIZE) 
      return false;//max size reach 
     if (index<0 || index > getSize())//index greater than array size? 
     { 
      cout<<"Invalid index location to insert"<<endl; 
      return false;//invalid location 
     } 

     for(int i = getSize()-1 ; i >= index;i--) 
     {//shift to the right 
      arraydata[i+1]=arraydata[i]; 
     } 
     arraydata[index] = item; 
     _size++; 
     return true; 
    } 

    string ListArray::toString() 
    { 
     ostringstream ostr; 
     ostr<<"["; 
     for(int i = 0; i < _size;i++) 
      ostr<<arraydata[i]<<' '; 
     ostr<<"]"<<endl; 
     return ostr.str(); 
    } 
}; 

我的main.cpp:

int main() 
{ 
    ListArray<char> myarray; 
    myarray.insert(0,'g'); 
    myarray.insert(0,'e'); 
    myarray.insert(1,'q'); 
    cout<<myarray.toString(); 
} 

我不能似乎弄清楚如何在一個子類中使用模板。當我編譯我的代碼,我得到以下錯誤:

error C2955: 'ListBase' : use of class template requires template argument list see reference to class template instantiation 'ListArray' being compiled

回答

9

您沒有爲Lis​​tBase指定模板參數。

template <class T> 
    class ListArray : public ListBase<T> 
            --- 
+0

OH您的權利。謝謝! – user1203499 2012-02-19 10:47:06