简体   繁体   English

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

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

I have a question. 我有个问题。 I want to call a constructor of "gameWindow" from the class "Game". 我想从类“ Game”中调用“ gameWindow”的构造函数。 The problem is that if I call it from the constructor it is initialising as a local variable (example A), if I define it in as a private member - I can not use arguments of a constructor. 问题是,如果我从构造函数中调用它,则它将初始化为局部变量(示例A),如果我将其定义为私有成员,则无法使用构造函数的参数。 How can I make gamewindowObj as a member from a constructor? 我怎样才能使gamewindowObj作为构造函数的成员?

//example А //示例А

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);
}

//example В //示例В

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){}

If you want gamewindowObj to be a data member and be initialized by the constructor's arguments, you can use member initializer list , eg 如果希望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) {
//  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM