Fre*_*rik 6 c++ constructor class object instantiation
我正在努力在另一个类中实例化一个类.我主要担心的是......我在哪里放置构造函数?在头文件中?在类文件中?或两者兼而有之?似乎没有什么工作正常.我会尝试尽可能简单.让我知道它是否太简单了;)这就是我应该如何思考它:
GameWorld.h:
#include "GameObject.h"
class GameWorld
{
protected:
GameObject gameobject;
}
Run Code Online (Sandbox Code Playgroud)
GameWorld.cpp:
#include "GameWorld.h"
void GameWorld::GameWorld()
{
GameObject gameObject(constrctor parameters);
}
//When I compile the program, the values in the gameObject, are not set to anything.
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的事情之一.由于显而易见的原因,将构造函数放在标题中也不起作用; 我无法从GameWorld中给它任何参数.
这样做的正确方法是什么?
编辑:哎呀.删除了一些无用的东西.
Aes*_*ete 10
您需要初始化GameObject包含类的初始化列表中的成员.
// In the GameWorld.h header..
class GameWorld
{
public:
GameWorld(); // Declare your default constructor.
protected:
GameObject gameobject; // No () here.
}
// In the GameWorld.cpp implementation file.
GameWorld::GameWorld() // No 'void' return type here.
: gameObject(ctorParams) // Initializer list. Constructing gameObject with args
{
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1443 次 |
| 最近记录: |