简体   繁体   English

如何在嵌套类中初始化成员? C ++

[英]How to initialize members in nested class? C++

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 假设我想将直径,宽度和体积设置为1,就像我将x设置为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 . 您的类声明了嵌套类的wheelsengine ,但它实际上并不包含wheels类型或类型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 . wheelsengine只是类型,你的car结构中没有这些类型的数据成员,唯一的数据成员是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) {}

Live Demo 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM