How do I initialize an array when an object is created?
I'm not sure how to use array variables with objects. How do you initialize an array when an object is created. 开发者_C百科An array that is a data member of an object.
I'm hoping to use an initialization list.
If your compiler supports it, you can do it like this:
struct Foo
{
int n[5];
Foo() :n{1,2,3,4,5} {}
};
Soon enough, that will be standard. GCC supports it now, I'm not sure what other compilers do.
An array member variable can only be default-initialized, you cannot provide explicit initialization values.
struct Foo {
Foo() : bar() {} // Default-initialize bar, for int this means initialize with 0
int bar[10];
};
If you want anything else, you'll have to assign in the constructor body.
struct Foo {
Foo() : bar() {
bar[3] = 1;
}
int bar[10];
};
精彩评论