CyberLuc CyberLuc - 1 year ago 263
C++ Question

C++ using new to create object array with initializer

I wrote a class, something like this (just for demonstration) :

class cls{
cls(int a):value(a){}
int value;

And I want to dynamically create an array, each element initialized to a specific value like 2:

cls *arr = new cls[N](2);

But g++ reported 'error: parenthesized initializer in array new'.

I searched the Internet, but only to find similar questions about basic types like
, and answer is NO WAY.

Suppose the class must be initialized, how to solve the problem? Do I have to abandon constructer?

Answer Source

You can:

cls *arr = new cls[3] { 2, 2, 2 };

If you use std::vector, you can:

std::vector<cls> v(3, cls(2));


std::vector<cls> v(3, 2);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download