2011-08-06 30 views
0

来自Java,PHP背景,我试图进入C++。我想在一个结构中存储一个数组。我的问题是在初始化结构之后指定数组的大小。结构中的数组,指针[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; 

什么我需要改变,以解决这一问题?

回答

0
struct SpriteAnimation { 
    // ... 
    int parts;     // total number of animation-parts 
    unsigned int * textures; // array to store all animation-parts 
    // ... 
}; 

只有当您声明成员内联时,才可以使用type name[]语法。比任何你可以用手动分配的存储尝试

struct SpriteAnimation { 
    std::vector<unsigned int> textures; // array to store all animation-parts 
    size_t num_parts() const { return textures.size(); } 
}; 

这是迄今为止更安全,更模块化:

+0

然后将它与'bg_anim.textures = new unsigned int [bg_anim.parts];'一起使用是否正确? – Ben

+0

当你复制你的结构时会发生什么?发生异常时会发生什么? –

+0

@Ben yes工作正常,事实上它之前不正确,因为texture是一个动态分配的数组,应该显示为一个指针。如果您希望使用C++,则应该查找类,因为您使用的是c样式语法。还要记得在结尾 – Will03uk

9

在现代C++中,你可以使用一个动态容器内“阵列”。用法:

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 
+2

Downvoter删除[]数组,小心解释你的反对意见吗?我明白,这不是做C的“C数组方式”,但是这个问题需要一个C++解决方案,而C++的惯用和道德方式是使用(异常安全和资源管理以及单一责任)容器作为构建块。 –

+0

这是如何知道数组的大小(或'vector' - 请你能解释一下这个区别吗?)? push_back()是否在每次调用时都创建一个新的调整大小?与约翰的解决方案相比,这会非常低效,还是我误解了某些东西? – Ben

+1

@Ben:解释'vector'的完整工作方式超出了这个意见,但是[阅读](http://www.cplusplus.com/reference/stl/vector/) - 是的,'push_back'确实附加一个新的元素,但这是由于魔法O(1)分期偿还。实际上,大多数C++标准库只能这样描述。 –

0

在编译时必须知道结构体的大小。

+0

他的意思是使用一个指针,而unsigned int *类型的静态大小是一个静态大小 – Will03uk

0

我通过下面的代码解决了这个问题。它可能有设计问题,所以请看下面的代码适合我。

#include <iostream> 
using namespace std; 
struct lol { 
    // ... 
    int parts;     // total number of animation-parts 
    unsigned int *texture; // array to store all animation-parts 
    // ... 
}; 

int main() { 
    // your code goes here 
    lol bg_anim; 
    bg_anim.parts = 3; 
    unsigned int *myarray = new unsigned int[bg_anim.parts]; 
    bg_anim.texture = myarray; 
    return 0; 
} 

请原谅我使用lol,而不是您指定的name.Do告诉我任何issues.And帮助我,如果有我的代码中的其他问题。 谢谢! :)

+0

,方法是'struct'不过是一个public类的类。更好的解决方案是使用类。 –