Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何初始化嵌套类中的成员?C++;_C++ - Fatal编程技术网

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

C++ 如何初始化嵌套类中的成员?C++;,c++,C++,我在初始化类内的类成员时遇到问题。 假设我想将直径、宽度和体积设置为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),

我在初始化类内的类成员时遇到问题。 假设我想将直径、宽度和体积设置为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) {}
我也试过这样做,但没有成功:

car::car() : x(1), wheels{ 1,1 } {}

您的类声明了嵌套类
wheels
engine
,但实际上不包含
wheels
engine
类型的成员变量。解决这个问题非常容易:

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
engine
只是类型,在
car
结构中没有这些类型的数据成员,唯一的数据成员是
x

我想你可能是想做这样的事:

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) {}