簡體   English   中英

如何在嵌套類中初始化成員? C ++

[英]How to initialize members in nested class? 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), wheels::diameter(1), wheels::width(1) {}

我也試過這樣做,但沒有運氣:

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

您的類聲明了嵌套類的wheelsengine ,但它實際上並不包含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) {}
};

wheelsengine只是類型,你的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) {}

現場演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM