我有一个类让我们说 aClass
class aClass
{
public:
int data;
aClass(): data(-1) { //default constructor
}
aClass(int x): data(x) { //int constructor
};
如果我创建一个像
这样的数组aClass* arr=new aClass[10];
问题一:
我在想没有 aClass
对象被创建,因为它只是一个数组的声明,但在我测试的程序中它看起来像 arr[0]
到 arr[9]
都指向由其类中的默认构造函数创建的aClass
对象?因为我测试过程序,结果是a[0].data=-1
一直到a[9].data=-1
。
问题 2:如果对象是使用其默认构造函数创建的,我应该如何创建一个包含由 int 构造函数创建的对象的数组?显然我不能写这样的代码
aClass* arr=new aClass(2015)[10];
最佳答案
Quesntion 1: I was thinking no aClass object has been created since it is just a declaration of an array
你想错了。它是一个指针 的声明,它用new aClass[10]
的返回值初始化。它构造一个包含 10 个对象的数组。
but in a program that I tested it looks like arr[0] to arr[9] all points to a aClass object created by default constructor in its class?
是的,你的观察是正确的。
Question 2: if objects are created with their default constructor, how am I supposed to create an array that has objects created by int constructor?
从 c++11 开始,您可以使用列表初始化:aClass *foo = new aClass[3]{1, 2, 3};
正如克里斯在评论中指出的那样。
您可能想改用 std::vector。有 std::vector::vector(size_type n, const value_type& val)
用于构建拷贝,自 c++11 起:std::vector::vector(initializer_list<value_type>)
对于不同的值。
即使在 c++11 之前,使用静态/自动数组聚合初始化也是可能的:
aClass foo[3] = { 1, 2, 3 };
关于c++ - 默认构造函数自动创建的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29852136/