简体   繁体   English

用另一个类成员C ++初始化一个类成员

[英]Initializing a class member with another class member C++

I have a class with two different class objects as members. 我有一个包含两个不同类对象的类。 I want to initialize one of the members with another, but so far I can't seem to get this to work. 我想用另一个成员来初始化其中一个成员,但是到目前为止,我似乎无法使它起作用。

For example, Game game(&input); 例如, Game game(&input); contains an error that there must be a type specified. 包含必须指定类型的错误。 How might I go about doing this? 我该怎么做呢?

class KApp { 
private:
    Input input;
    Game game(&input);

};


class Input {
    Input() {};
};

class Game {
private:
    Input* input;
public:
    Game(Input & inp) : input(&inp) {}
    Game(Input* inp) : input(inp) {}
};

Try something like this 试试这个

class KApp { 
private:
    Input input;
    Game game;
    KApp() : game(&input) {}
};

What is going on with Game game(&input); Game game(&input);是怎么回事Game game(&input); is that you're declaring a member game which the compiler has picked up as a function declaration and is complaining that the parameter doesn't have a type. 就是说您要声明一个成员game ,编译器已将其提取为函数声明,并且抱怨该参数没有类型。

This way, you're explicitly calling Game::Game(Input*) in the constructor of KApp (at which point input should be initialized using its default constructor). 这样,您可以在KApp的构造函数中显式调用Game::Game(Input*) (此时应使用其默认构造函数初始化输入)。

edit - Input* vs Input& 编辑-输入*与输入&

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

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