You can write like this:
int test[] = {1,2,3,4};
but what if you want to use a pointer and allocate it with new?
int *test2;
test2 = new int[]{1,2,3,4};
This开发者_JAVA技巧 does not work, what is the syntax or is it possible?
This is one of the short-comings of current standard C++. Initialization is not uniform. Your best hope is uniform initialization in C++0x, but for the mean while you can assign the values after creating the array, e.g.
int *test2;
test2 = new int[4]; // Note that you still have to specify the size in C++0x
test2[0] = 1;
test2[1] = 2;
test2[2] = 3;
test2[3] = 4;
If you compiler supports C++0x
int *test2;
test2 = new int[4] {1,2,3,4}; // Initializer list in C++0x
would work. However you should always use std::vector
instead of C style arrays while writing good C++ code.
The first syntax is called aggregate initialization, and you cannot apply it to a dynamically allocated array. When allocating dynamically you must provide the number of elements that you want to initialize inside the square brackets and (optionally) the default value in parenthesis (if you want the array initialised). The default value will be the same (if present) for all elements.
You may want to look into the boost::assign library that may have support for this type of initialization (not sure). Alternatively you can (at the cost of more code) do it yourself for POD types:
int * array = new int[4];
{
int values[] = { 1,2,3,4 };
memcpy( array, values, sizeof(values) );
}
Or for non-pod types:
type * array = new type[4];
{
type values[] = { 1,2,3,4 }; // assuming type(int) constructor
std::copy( values, values+4, array ); // better to use some magic to calculate size
}
At any rate both of those solutions require allocating locally and the copying (bit-size/c++) into the dynamically allocated memory.
精彩评论