【问题标题】:How to use arguments from constructor to call a constructor of another class in C++?如何使用构造函数中的参数在 C++ 中调用另一个类的构造函数?
【发布时间】:2017-12-31 01:24:44
【问题描述】:

我有一个问题。我想从“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){}

【问题讨论】:

  • 使用构造函数初始化列表:Game(int inWidth,....) : gamewindowObj(inWidht,...) {}

标签: c++ oop constructor initialization


【解决方案1】:

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

【讨论】:

  • 非常感谢@songyuanyao
  • 另外,对于 OP。如果不仅仅是重用参数的问题,有时值得编写一个可用于初始化gameWindow 的函数。 gameWindow&& initGameWindow(int arg1, int arg2) {/*complex stuff*/}
猜你喜欢
  • 2014-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-28
  • 2017-01-05
  • 2012-06-22
  • 1970-01-01
  • 2023-04-03
相关资源
最近更新 更多