C ++:动态分配使用非默认的构造结构的成员数组 [英] C++: dynamically allocating a member array of structs using non-default constructor
本文介绍了C ++:动态分配使用非默认的构造结构的成员数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有:
struct a_struct
{
int an_int;
a_struct(int f) : an_int(f) {}
a_struct() : an_int(0) {}
};
class a_class
{
a_struct * my_structs;
a_class() {...}
};
我可以这样做:
a_class() {my_structs = new a_struct(1)}
//or
a_class() {my_structs = new a_struct [10]}
但我的不能的事:
a_class() {my_structs = new a_struct(1) [10]}
//or
a_class() {my_structs = new a_struct() [10]}
有没有正确的语法得到这个工作?或一个简单的变通?
Is there any correct syntax to get this to work? Or an easy work around?
推荐答案
如果使用STL是一个选项,你可以使用std ::载体,而不是一个动态数组。
If using the STL is an option, you could use std::vector instead of a dynamic array.
我的认为的,这将工作:
std::vector<a_struct> my_structs;
my_structs.assign(10, 1);
如果不是,这应该:
my_structs.assign(10, a_struct(1));
这篇关于C ++:动态分配使用非默认的构造结构的成员数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文