开发者

C++ Vector Of Base Class Containing Derived Types

开发者 https://www.devze.com 2023-02-16 22:00 出处:网络
I have a several classes Deman开发者_开发问答dBuilding, Factory, Farm and some others. I want to store instances of these in a single 2d array, I did this by making a base class, Building, which does

I have a several classes Deman开发者_开发问答dBuilding, Factory, Farm and some others. I want to store instances of these in a single 2d array, I did this by making a base class, Building, which does nothing but allows me to do this: (Note that the second vector is because it is a 2d vector for storing these buildings on a map)

vector<vector<Building*> > map;

Instead of this:

vector<vector<DemandBuilding*> > demand_buildings;
vector<vector<Factory*> > factories;
vector<vector<Farm*> > farms;
//etc...

(I'm away from my computer so I'm not sure that this is legal C++, although I think it is) To me this looks like an incorrect use of inheritance, is it?

EDIT: Thanks for helping that there is nothing conceptually wrong with this but I have since realized that doing this wont help my situation, thanks anyway.


Conceptually there's nothing wrong with this - it all depends on how you use it. If you find yourself having to cast a lot, you may need to rethink the design.

Also, you very likely should have a virtual destructor, if you delete a Building * and the destructor isn't virtual, the subclass destructor is not executed.


The second vector is not needed, just use:

vector<Building*> buildings;

And for 2d array you can have:

vector< vector<Building*> > buildingMatrix;

or if you know the size of the 2d array at compile time:

Building* buildingMatrix[SOME_CONST_SIZE_1][SOME_CONST_SIZE_2];

So you can have here pointers of all your buildings.

Also you may consider putting all the common methods of your diffident buildings into base class Building. Make them virtual as appropriate, use virtual destructor in case you will need to delete particular building correctly with Building pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消