C++:使用非默认构造函数动态分配结构的成员数组 [英] C++: dynamically allocating a member array of structs using non-default constructor

查看:33
本文介绍了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::vector 而不是动态数组.

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屋!

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