不同类型的用户自定义数组 类

Array of different types of user defined classes

所以基本上我想找出一种创建数组的方法,其中每个元素都可以是不同的类型(我正在创建一个 Equipemnt,其中包含玩家拥有的所有物品,其中每个物品都是独立的 class) classes (B,C,D) 中的每一个都有一个名称完全相同的方法,在单击特定的 tab[] 元素时使用。

不幸的是,尝试使用 union 并没有解决我的问题。

示例:

union A
{
B b;
C c;
D d
}
A tab[3];
tab[0]=B item1(a,b,c,...);
tab[1]=C item2;
tab[2]=D item3;

使用std::variant类型

std::vector<std::variant<B, C, D>>

最好创建名为 element 的父 Class,然后您可以为您的项目创建子 classes,并将子 classes 的所有对象存储在父 class 的数组中=16=]类型

//creating objects of items
B gun;  
C knife;

//an array
Element items[2]; 

//adding objects of your items in the array 
items[0]=gun;
items[1]=knife;

顺便说一句最好使用向量来创建数组