创建实际对象数组C ++

时间:2012-03-20 13:15:38

标签: c++ arrays object

我想创建一个数组来存储实际的对象,而不是指向C ++中的对象的指针?

有人可以解释我该怎么做?是使用矢量还是直接更好:

Student s [10];

OR

Student s [10][];

3 个答案:

答案 0 :(得分:4)

使用:

Student s [10];

创建一个包含10个Student个实例的数组。

我认为Student s [10][];无效。

但是使用C ++我不会使用C类型数组,最好使用类似std::vector或C ++ 0x std::array的类,这些类可能不适用于最新的标准库/编译器。

以上std::vector

的示例
#include <vector>

...

std::vector<Student> students(10);

使用std::array

#include <array>

...

std::array<Student, 10> students;

答案 1 :(得分:2)

不要使用数组。数组是C而不是c ++。请改用std::vector,这是处理此问题的C ++方法。

答案 2 :(得分:1)

我建议使用std :: vector,如果你想使你的数组​​可以增长,否则只需要使用学生[10];对于10个物体。