如何声明一个类没有默认构造函数的对象数组? [英] How do I declare an array of objects whose class has no default constructor?

查看:23
本文介绍了如何声明一个类没有默认构造函数的对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个类只有一个带参数的构造函数,如何声明一个数组?我知道在这种情况下推荐使用 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));

这篇关于如何声明一个类没有默认构造函数的对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆