[英]How to call constructor of a class that is within another class in C++?
[英]How to use arguments from constructor to call a constructor of another class in C++?
我有個問題。 我想從類“ 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){}
如果希望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.