问题描述
我没有做任何的C ++编程相当长的一段时间,我决定,我会更动它在我的业余时间一点点,所以我决定给我写一个小数据库程序只是为了好玩,我有麻烦创建模板类对象的数组。
I haven't done any C++ programming for quite some time and I decided that I would mess around with it a little bit in my spare time so I decided to write me a little database program just for fun and I'm having trouble with creating an array of templated class objects.
我已经是这样的类,我想用它来重新present一个字段在数据库中记录。
What I have is this class which I want to use to represent a field in a database record.
template <class T, int fieldTypeId>
class Field
{
private:
T field;
int field_type;
public:
// ...
};
和我想使用这个类的数组使用此类重新present记录在数据库中。
And I want to use an array of that class to represent a record in a database using this class.
class Database_Record
{
private:
int id;
Field record[];
public:
Database_Record(int);
Database_Record(int, Field[]);
~Database_Record();
};
在哪里我被困在位于 Database_Record
类阵列的创建,因为这是模板类对象,每个元素可能是一个不同类型的数组我不知道我需要怎样声明,因为该数组。就是我试图做甚至有可能还是我将它的错误的方式?任何帮助将大大AP preciated。
Where I'm stuck at is the creation of the array in the Database_Record
class since that is an array of templated class objects with each element possibly being of a different type and I'm not sure how I need declare the array because of that. Is what I'm trying to do even possible or am I going about it the wrong way? Any help would be greatly appreciated.
推荐答案
字段&LT; T1&GT;
和字段&LT; T2&GT;
是两个完全不同的类型。要在矢量对待他们,你需要generialize然后某处。你可以写 AbstractField
和
Field<T1>
and Field<T2>
are two completely different types. To treat them in a vector you need to generialize then somewhere. You may write AbstractField
and
struct AbstractField{
virtual ~AbstractField() = 0;
};
template<class T,int fieldTypeId>
class Field: public AbstractField{
private:
T field;
public:
const static int field_type;
public:
virtual ~Field(){}
};
class Database_Record{
std::vector<AbstractField*> record;
public:
~Database_Record(){
//delete all AbstractFields in vector
}
};
然后保持 AbstractField
的矢量
。还可以使用矢量
而不是 []
。使用 AbstractField *
而不是 AbstractField
和写入至少一个纯虚在 AbstractField
。
and then keep a vector
of AbstractField
. also use vector
instead of []
. Use AbstractField*
instead of AbstractField
and write at least one pure virtual in AbstractField
.
您可能会使 AbstractField
纯虚的析构函数。不要忘记删除所有 AbstractField
秒。在〜Database_Record()
you may make the destructor of AbstractField
pure virtual. and don't forget to delete all AbstractField
s. in ~Database_Record()
这篇关于如何创建模板类对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!