class Resources{
protected:
int size;
char repchar; //Representing Char
public:
Resources(int size=0,char repchar=' ');
char getchar();
int getsize();
//copy const
//destructor };
class Bone:public Resources{
private:
int BoneScore;
public:
Bone(int size,char repchar,int BoneScore);
};
class Trap:public Resources{
/* private:
bool active=false;*/
public:
Trap();
// bool activehigh();
};
class Food:public Resources{
private:
int energy;
public:
Food(int size,char repchar,int energy);
};
class Water:public Resources{
private:
int energy;
public:
Water();
};大家好,基本上我是C++.I的初学者我正在尝试创建一个基于地图的游戏。我会把资源随机放到地图上,然后他们会收集turn.At的结束,程序将计算来自骨骼的点数,并决定关于winner.Therefore,我想存储的资源由玩家.What我暗示的是,我想存储在一个variable.Thank中的不同类别的事实,为您提供帮助提前。我有4种不同的资源骨骼,陷阱,水,食物。
发布于 2020-06-09 03:40:11
这被称为多态:
class base {};
class child1 : public base{};
class child2 : public base{};
base* b1 = new child1();
base* b2 = new child2();将我的base类视为您的Resource类。你可以这样做:
typedef std::list<Resource*> Resources;
Resources resources;
// Map setup
resources.push_back(new Bone());
resources.push_back(new Trap());
resources.push_back(new Water());
// Interact with each one:
for(auto& resource : resources)
resource->getsize(); // Call a method from Resource::
// Interact with traps:
for(auto& resource : resources)
if (resource->getchar() == 't') // If the resource is a trap
dynamic_cast<Trap*>(resource)->trigger(); // Trap-specific method
// clean-up
for(auto it = resources.begin(); it != resources.end(); )
{
delete *it;
it = resources.erase(it);
}https://stackoverflow.com/questions/62269629
复制相似问题