C++抽象类模板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9348447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ abstract class template
提问by user1203499
I have the following code:
我有以下代码:
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;
};
My second file defines a subclass:
我的第二个文件定义了一个子类:
#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();
}
};
My main.cpp:
我的 main.cpp:
int main()
{
ListArray<char> myarray;
myarray.insert(0,'g');
myarray.insert(0,'e');
myarray.insert(1,'q');
cout<<myarray.toString();
}
I can't seem to figure out how to use a template with a subclass. When I compile my code, I get the following error:
我似乎无法弄清楚如何使用带有子类的模板。当我编译我的代码时,我收到以下错误:
error C2955: 'ListBase' : use of class template requires template argument list see reference to class template instantiation 'ListArray' being compiled
错误 C2955:“ListBase”:使用类模板需要模板参数列表,请参阅正在编译的类模板实例化“ListArray”的参考
回答by Karoly Horvath
You didn't specify the template parameter for ListBase.
您没有为 ListBase 指定模板参数。
template <class T>
class ListArray : public ListBase<T>
---
回答by Mat
class ListArray : public ListBase
should be
应该
class ListArray : public ListBase<T>
And you've got a bunch of problems with accessing the base class members. See: Accessing inherited variable from templated parent class.
并且您在访问基类成员时遇到了很多问题。请参阅:从模板化父类访问继承的变量。