I have a problem with initializing members of class inside class. Let's say that I want to set diameter, width and volume to 1 just like I set x to 1
struct car {
int x;
struct wheels {
int diameter;
int width;
};
struct engine {
int volume;
};
car();
car(wheels w, engine e);
};
car::car() : x(1), wheels::diameter(1), wheels::width(1) {}
I also tried do it like this but with no luck:
car::car() : x(1), wheels{ 1,1 } {}
Your class declares the nested classes wheels
and engine
, but it doesn't actually contain member variables of type wheels
or type engine
. It's pretty easy to fix this:
struct car {
struct Wheels {
int diameter;
int width;
};
struct Engine {
int volume;
};
int x;
Wheels wheels;
Engine engine;
car() : x(1), wheels{1,1}, engine{} {}
car(Wheels w, Engine e) : x(1), wheels(w), engine(e) {}
};
wheels
and engine
are just types, there are no data members of those types in your car
struct, the only data member is x
.
I think you probably meant to do something like this instead:
struct car {
struct wheels {
int diameter;
int width;
};
struct engine {
int volume;
};
int x;
wheels w;
engine e;
car();
car(wheels w, engine e);
};
car::car() : x(1), w{1, 1}, e{1} {}
car::car(wheels w, engine e) : x(1), w(w), e(e) {}
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.