I'm trying to (force) initialize an array of 3 class elements in another class (I know I could use a vector and initializer list or so but I want to know if there's any possibility this way) and let's say I've this code for ex:
class A{
// CODE HERE, doesn't really matter
}
and then
class B{
string name;
A array[3]; <-- here's the point. I want array of 3 members of class A
public:
B(string name_, A a, A b, A c) : name(name_), array[0](a), array[1](b), array[2](c){} // Here's the problem. I can't initialize this way, it always give me some sort of error and array isn't recognized as a class variable (no color in the compiler like 'name' for ex shows and it should be).
}
if for some reason I don't initialize in the prototype and just do it inside the function like this->array[0] = a and so on, it works. But I'd like to know a way to do it inline like I displayed above.
You can do it like this in C++11
class B{
string name;
A array[3];
public:
B(string name_, A a, A b, A c)
: name(name_),
, array{a, b, c}
{
}
};
After fixing the simply typos from your example you can use a brace initializer list for your array like this:
class A{
// CODE HERE, doesn't really matter
};
class B{
string name;
A array[3]; // <-- here's the point. I want array of 3 members of class A
public:
B(string name_, A a, A b, A c) : name(name_), array{a,b,c} {}
// ^^^^^^^
};
Dereferencing by index isn't possible at this point.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.