[英]Making an array of a certain struct within the struct.
我有一个叫做场景的结构。 在名为scene的结构中,我需要创建一个其他场景对象的数组。 这可能吗?
不,因为在scene
完全定义之前,编译器不知道它有多大,并且不知道制作阵列的大小。
但是,你可以有一个指向 scene
的指针数组,因为指针(不计算指向成员的指针和其他奇怪的东西 - 感谢Nawaz)都是相同的大小:
class scene {
scene* array[20];
};
或者,您可以存储指向使用new[]
分配的动态数组并使用delete[]
解除分配的指针:
class scene {
scene() : array(new scene[20]) { }
~scene() { delete[] array; }
scene* array;
};
或者更确切地说,存储一个vector<scene>
,一个scene
vector
:
class scene {
vector<scene> array;
};
并使用vector
,您将获得一个可调整大小的数组,没有手动内存管理。
是。 你可以做到这一点。 但是你要将成员声明为指针 :
struct scene
{
//other members
scene *children; //this is what you need.
//you cannot make it like : scene children[100];
};
然后创建动态数组:
scene parent;
parent.chidren = new scene[100]; //100 children!
请记住,您必须自己分配和释放内存。
或者,您可以使用std::vector<scene*>
或boost::ptr_vector<scene>
。
当然有可能。
伪代码:
struct Scene {
int id;
Scene* scenes;
};
PS。 你可以很容易地测试一下 - 不要太懒。 ;)
如果你使用std::vector
你可以这样做。 这是我昨天写的一些代码:
#include <vector>
struct ChangeList // Tree of changes in a tree of values
{
int index ;
std::vector<ChangeList> Changes ;
} ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.