如何使用构造函数中的参数来调用C++中另一个类的构造函数?

pet*_*huk 1 c++ oop constructor initialization

我有个问题.我想从"Game"类中调用"gameWindow"的构造函数.问题是,如果我从构造函数中调用它,它将初始化为局部变量(示例A),如果我将其定义为私有成员 - 我不能使用构造函数的参数.如何将gamewindowObj作为构造函数的成员?

//示例А

class Game{
public:
    Game(int inWidth, int inHeight, char const * Intitle);
};

Game::Game(int inWidth, int inHeight, char const * Intitle){
    gameWindow gamewindowObj=gameWindow(inWidth, inHeight, Intitle);
}
Run Code Online (Sandbox Code Playgroud)

//示例В

class Game{
public:
    Game(int inWidth, int inHeight, char const * Intitle);
private:
    gameWindow gamewindowObj=gameWindow(inWidth, inHeight, Intitle);
};
Game::Game(int inWidth, int inHeight, char const * Intitle){}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 7

如果您想gamewindowObj成为数据成员并由构造函数的参数初始化,则可以使用成员初始化列表,例如

class Game{
public:
    Game(int inWidth, int inHeight, char const * Intitle);
private:
    gameWindow gamewindowObj;
};

Game::Game(int inWidth, int inHeight, char const * Intitle) 
    : gamewindowObj(inWidth, inHeight, Intitle) {
//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
Run Code Online (Sandbox Code Playgroud)