c++ - 默认构造函数自动创建的数组元素?

标签 c++

我有一个类让我们说 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/

相关文章:

c++ - 无法将纹理应用于 Qt OpenGL 中的顶点网格

c++ - Visual Studio 2013 SDKDDKVer.h 及相关错误

c++ - 解决方案不适用于两个日期之间的天数

c++ - 读取字符串的长度,然后反转/反转字符串

c++ - 仅获取整数作为输入,代码未按预期工作

C++动态分配内存

c++ - Fd 大于 1024 时 Select 和 FD_SET 的行为

c++ - 在 MS VC++ 2005 中调试堆损坏错误

c++ - 创建一个返回 std::mem_fn 或 boost::mem_fn 的通用包装器

c++ - const void (* 函数)