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

标签 c++ oop constructor initialization

我有一个问题。我想从“游戏”类中调用“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/

相关文章:

java - 为什么我不能在 Java 的函数中创建对象?

Typescript Private or protected member 'something' 无法在类型参数上访问

c# - 在不需要许多并行对象模型的情况下设计 MVC/EF 系统

c++ - 如何在类的成员函数中调用复制构造函数?

c++ - 支持两个具有不同语义的整数构造函数

c++ - Visual Studio 2010 C++ 编译器 - 编译时获取当前行号

c++ - std type_traits 与 Qt type_traits 冲突

javascript - 为什么 Promise 构造函数如此冗长?

c++多态性,派生类的名称解析

c++ - 在映射中插入一对时,C++ 是否需要额外的代码?