矢量可以有3种不同的数据类型C ++ [英] Vector that can have 3 different data types C++
问题描述
我想在C ++中创建一个可以存储3种不同数据类型的向量。我不想使用boost库。
类似:
I'm trying to make a vector in C++ that can store 3 different data types. I do not want to use the boost library. Something like:
vector<type1, type2, type3> vectorName;
我需要制作模板吗?
推荐答案
在同一个向量中存储多个类型的最简单的方法是使它们为子类型
The easiest way to store multiple types in the same vector is to make them subtypes of a parent class, wrapping your desired types in classes if they aren't classes already.
class Parent
{
//anything common to the types should be declared here, for instance:
void print() //make this virtual if you want subclasses to override it
{
std::cout << "Printing!";
}
virtual ~Parent(); //virtual destructor to ensure our subclasses are correctly deallocated
};
class Type1 : public Parent
{
void type1method();
};
class Type2 : public Parent
{
void type2Method();
};
class Type3 : public Parent
{
void type3Method();
};
$ b <可以存储指向子类型的指针的指针:
You can then create a vector of Parent
pointers that can store pointers to the child types:
std::vector<Parent*> vec;
vec.push_back(new Type1);
vec.push_back(new Type2);
vec.push_back(new Type3);
直接从向量访问元素时,您只能使用属于 Parent
。例如,您可以写:
When accessing elements directly from the vector, you'll only be able to use members that belong to Parent
. For instance, you can write:
vec[0]->print();
但不是:
vec[0]->type1Method();
由于元素类型已声明为 Parent *
且 Parent
类型没有 type1Method
。
As the element type has been declared as Parent*
and the Parent
type has no type1Method
.
如果需要访问子类型特定成员,可以将 Parent
指针转换为子类型指针,如下所示:
If you need to access the subtype-specific members, you can convert the Parent
pointers to subtype pointers like so:
Parent *p = vec[0];
Type1 *t1 = nullptr;
Type2 *t2 = nullptr;
Type3 *t3 = nullptr;
if (t1 = dynamic_cast<Type1*>(p))
{
t1->type1Method();
}
else if (t2 = dynamic_cast<Type2*>(p))
{
t2->type2Method();
}
else if (t3 = dynamic_cast<Type3*>(p))
{
t3->type3Method();
}
虽然通常认为避免这种显式类型分支
Although it's generally considered a better idea to avoid this kind of explicit type-branching and instead rely on virtual methods.
如果使用动态分配,请务必删除指针,然后再将其从向量中删除,如上面的示例所示。或者,使用智能指针(可能 std :: unique_ptr
,并让你的内存照顾自己:
Be sure to delete the pointers before removing them from the vector if you use dynamic allocation, as I did in the example above. Alternatively, use smart pointers (probably std::unique_ptr
and let your memory take care of itself:
std::vector<std::unique_ptr<Parent>> vec;
这篇关于矢量可以有3种不同的数据类型C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!