我有一个问题。我想从“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);
}
//示例В
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){}
答案 0 :(得分:7)
如果您希望gamewindowObj
成为数据成员并由构造函数的参数初始化,则可以使用member initializer list,例如
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) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}