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

How to use arguments from constructor to call a constructor of another class in C++?

本文关键字:构造函数 另一个 C++ 参数 何使用 调用      更新时间:2023-10-16

我有一个问题。我想从类"游戏"中调用"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){}

如果您希望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) {
//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}