如何声明一个类没有默认构造函数的对象数组?

如何声明一个类没有默认构造函数的对象数组?

问题描述:

如果一个类只有一个带参数的构造函数,如何声明一个数组?我知道在这种情况下推荐使用 vector .例如,如果我有一个班级

If a class has only one constructor with one parameter, how to declare an array? I know that vector is recommended in this case. For example, if I have a class

class Foo{

public:
Foo(int i) {}

}

如何声明一个包含 10000 个 Foo 对象的数组或向量?

How to declare an array or a vector which contains 10000 Foo objects?

对于数组,您必须在定义数组的位置为数组的每个元素提供一个初始值设定项.

For an array you would have to provide an initializer for each element of the array at the point where you define the array.

对于向量,您可以为向量的每个成员提供一个实例进行复制.

For a vector you can provide an instance to copy for each member of the vector.

例如

std::vector<Foo> thousand_foos(1000, Foo(42));