如何创建动态分配的对象数组而不使用默认构造函数? [英] How to create a dynamically allocated array of objects and not use the default constructor?

查看:53
本文介绍了如何创建动态分配的对象数组而不使用默认构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动态创建的对象数组需要使用非默认构造函数,我遇到的问题是语法.在我看来,我能够做到这一点

The dynamically created array of objects need to use a non-default constructor, and the problem I'm running into I think is the syntax. In my mind, the fact that I'm able to do this

int * somePtr = new int[5];

意味着我应该能够做到这一点

means that I should be able to do this

IntegerSet* someSet = new IntegerSet(this->getLength())[5];

其中IntegerSet是我制作的代表整数集的类.此代码在IntegerSets成员函数之一内部发生.当我尝试此操作时,出现语法错误无法从IntegerSet转换为IntegerSet *"

where IntegerSet is a class I have made that represents an integer set. this code is happening inside one of IntegerSets member function. When I try this I get a syntax error "cannot convert from IntegerSet to IntegerSet*"

我理解这是什么意思,这两种类型不是等效的,但是除了第2部分必须传递参数列表这一事实之外,我看不到在第1部分和第2部分中所做的区别.作为构造函数.因此,我怀疑那部分代码语法错误

I understand what this means, the two types aren't equivalent, but I can't see the difference between doing what I did in part 1 and part 2, besides the fact that part 2 has to have an argument list passed as the constructor. So it is in that part of the code that I suspect I have the syntax wrong

推荐答案

new 表达式仅允许默认初始化, 您不能在单个 new中执行此操作表达式 .您可以做的就是分配原始内存,并使用新的展示位置一一构造对象(请参见此答案)"https://stackoverflow.com/q/4754763/1168156">没有默认构造函数的对象数组初始化)

new expression allows only default initialization, you can not do this within single new expression. What you could do is allocate raw memory and construct objects one by one using placement new (see this answer in Object array initialization without default constructor)

或更妙的是,不要使用C样式的数组.取而代之的是使用一些STL容器,例如 std :: vector 及其构造函数,其中第二个参数是一个将用于初始化元素的值:

Or yet even better, don't use C-style arrays. Instead, use some STL container such as std::vector and it's constructor, where the 2nd argument is a value that will be used to initialize elements:

std::vector<IntegerSet> integers(5, IntegerSet(this->getLength()) );

这篇关于如何创建动态分配的对象数组而不使用默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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