代码:
struct Base { ... };
struct A : public Base { ... };
struct B : public Base { ... };
struct C : public Base { ... };
是否可以创建一个包含该类型结构的数组? 示例/预期结果:
Type inheritedTypesOfStruct[3] = {A, B, C};
这样做的目的是我以后想创建一个对象,其中包含从数组中检索到的随机类。
最佳答案
您可以创建一个函数数组,每个函数返回一个基指针(或智能指针),每个指针都指向您的各种派生类的对象。例如
typedef std::unique_ptr<Base> base_ptr;
template<typename Derived>
base_ptr CreateObject()
{
return base_ptr(new Derived);
}
int main()
{
std::function<base_ptr(void)> f[3] = {
CreateObject<A>, CreateObject<B>, CreateObject<C>
};
base_ptr arr[10];
for (int i=0; i<10; ++i)
arr[i] = f[rand()%3]();
}
它正在运行:http://ideone.com/dg4uq
关于c++ - 如何在 C++ 中创建类数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8702649/