如何使用构造函数中的参数来调用C++中另一个类的构造函数?
How to use arguments from constructor to call a constructor of another class in C++?
我有一个问题。我想从类"游戏"中调用"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) {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}
相关文章:
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 关于复制构造函数的一个棘手问题
- C++构造函数,一个用于度,一个用于弧度
- 关于QLIST类型实例复制构造函数的一个奇怪问题
- 需要使班级(long_number)用构造函数和一个打印功能代表1到60的任何长度
- 运算符 = 不匹配,构造函数创建一个指针
- 为什么我不能在 c++ 类中声明一个空构造函数,该构造函数从一个具有私有构造函数的构造函数扩展而来
- 如何使构造函数接受一个非常量对象
- 初始值设定项列表,可变参数模板和构造函数推导:一个奇怪的情况
- shared_ptr的原始指针构造函数是一个错误吗?
- 当这个构造函数接受一个初始值设定项列表并委托一个向量时,是什么导致它委托给自己
- C++11使variadic构造函数了解一个初始化列表的初始化列表
- 为什么这个initializer_list构造函数是一个可行的重载
- 为什么我的Arduino类构造函数需要一个参数
- 内联构造函数和一个定义规则
- 如何通过构造函数将一个类的实例传递给另一个类
- 如何用g++构造在另一个文件中定义的类
- 在另一个类中使用自定义构造函数声明一个类
- 如何从另一个构造函数调用一个c++类的构造函数
- 模板中的构造函数不同:一个用于字符串,另一个用于其他任何东西