在通过构造函数传递变量的对象中创建对象 [英] create objects in object passing variables through constructor
问题描述
我一整天都在反对这个,多次访问谷歌.我有一个主对象需要在其构造函数中创建几个其他对象,主对象在其构造函数中获取变量,这些变量会传递给它创建的对象.
Been banging my head against this all day with many trips to google. I have a master object that needs to create several other objects in its constructor the main object gets variables in its constructor that are passed on to the objects it creates.
class WorldManager{
public:
WorldManager(int x, int y, int z){
//do stuff
}
}
class GameManager{
public:
WorldManager world;
GameManager(int x, int y, int z){
world(x,y,z);
}
}
出现错误
error: no matching function for call to `GAMEMANAGER::GraphicsManager(HWND__*&, int&, int&)'
它一直有效,直到我在世界级的构造函数中要求参数
it works untill I ask for args in the constructors of the world class
推荐答案
我认为你想要:
class GameManager{
public:
WorldManager world;
GameManager(int x, int y, int z) : world(x, y, z) { }
};
奇怪的冒号被称为初始化列表,它负责构造成员对象和父类以及其他一些事情.
The weird colon thing is called an initialization list, and it does construction of member objects and parent classes and a bunch of other things.
如果您要构造多个对象,请将它们添加到列表中:
If you have more than one object that you want to construct, add them to the list:
class GameManager{
public:
WorldManager world1, world2;
GameManager(int x, int y, int z) : world1(x, y, z), world2(x, y, z) { }
};
这篇关于在通过构造函数传递变量的对象中创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!