简体   繁体   中英

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); 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); 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.

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).

edit - Input* vs Input&

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.

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