C ++使用new创建带有初始化程序的对象数组 [英] C++ using new to create object array with initializer
本文介绍了C ++使用new创建带有初始化程序的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个课,像这样(只是为了演示):
I wrote a class, something like this (just for demonstration) :
class cls{
public:
cls(int a):value(a){}
private:
int value;
};
我想动态创建一个数组,每个元素都初始化为一个特定值,如2: p>
And I want to dynamically create an array, each element initialized to a specific value like 2:
cls *arr = new cls[N](2);
但是g ++报告错误:新数组中带有括号的初始化程序。
But g++ reported 'error: parenthesized initializer in array new'.
我搜索了Internet,但只是找到关于基本类型的类似问题,例如 int
和 double
,并且答案是不可能的。
I searched the Internet, but only to find similar questions about basic types like int
and double
, and answer is NO WAY.
假设必须初始化该类,如何解决问题?我必须放弃构造函数吗?
Suppose the class must be initialized, how to solve the problem? Do I have to abandon constructer?
推荐答案
您可以:
cls *arr = new cls[3] { 2, 2, 2 };
如果使用 std :: vector
,您可以:
std::vector<cls> v(3, cls(2));
或
std::vector<cls> v(3, 2);
这篇关于C ++使用new创建带有初始化程序的对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文