我有 Java、PHP 背景,正在尝试学习 C++。我想在结构中存储一个数组。我的问题是在初始化结构后指定数组的大小。
这是我的结构代码:
struct SpriteAnimation {
// ...
int parts; // total number of animation-parts
unsigned int textures[]; // array to store all animation-parts
// ...
};
这里是主要功能:
SpriteAnimation bg_anim;
bg_anim.parts = 3;
unsigned int *myarray = new unsigned int[bg_anim.parts];
bg_anim.textures = myarray;
我需要更改什么才能解决此问题?
最佳答案
在现代 C++ 中,您将为内部“数组”使用动态容器:
struct SpriteAnimation {
std::vector<unsigned int> textures; // array to store all animation-parts
size_t num_parts() const { return textures.size(); }
};
到目前为止,这比您尝试使用手动分配的存储空间要安全得多,模块化程度也更高。用法:
SpriteAnimation x;
x.textures.push_back(12); // add an element
x.textures.push_back(18); // add another element
SpriteAnimation y = x; // make a copy
std::cout << "We have " << x.num_textures() << " textures." std::endl; // report
关于c++ - 结构中的数组,指针 [C++ 初学者],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6969055/