gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:39:43 24 4
gpt4 key购买 nike

我有一个问题。我想从“游戏”类中调用“gameWindow”的构造函数。问题是,如果我从构造函数中调用它,它将初始化为局部变量(示例 A),如果我将它定义为私有(private)成员——我不能使用构造函数的参数。如何使 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);
}

//示例B

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成为一个数据成员,并由构造函数的参数初始化,你可以使用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) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}

关于c++ - 如何使用构造函数中的参数调用 C++ 中另一个类的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45297858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com