create objects in object passing variables through

2019-08-03 17:53发布

问题:

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);
  }
}

I get error

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

回答1:

I think that you want:

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) { }
};


标签: c++ oop