创建实际对象数组C++

Create Array of Actual Objects C++

本文关键字:数组 C++ 对象 创建      更新时间:2023-10-16

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

有人能解释一下我该怎么做吗?是使用矢量更好还是直接像一样

Student s [10];

Student s [10][];

使用:

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;

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

如果您想使数组可增长,我建议使用std::vector,否则只使用Student students[10];对于10个对象。