如何创建模板化类对象的数组? [英] How to create an array of templated class objects?
问题描述
我已经有很长一段时间没有做过任何 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.
我拥有的是这个类,我想用它来表示数据库记录中的一个字段.
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:
// ...
};
并且我想使用该类的数组来表示使用该类的数据库中的记录.
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
类中创建数组,因为这是一个模板化类对象的数组,每个元素可能是不同的类型,我不确定因此我需要如何声明数组.我正在尝试做的事情是可能的还是我以错误的方式去做?任何帮助将不胜感激.
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.
推荐答案
Field
和 Field
是两种完全不同的类型.要在向量中处理它们,您需要在某处进行泛化.你可以写 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
的vector
.也使用 vector
而不是 []
.使用 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
s.在 ~Database_Record()
you may make the destructor of AbstractField
pure virtual. and don't forget to delete all AbstractField
s. in ~Database_Record()
这篇关于如何创建模板化类对象的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!