如何在一个数组/容器中使用不同的对象? 我是C++初学者,做我的第一个2D游戏(只是为了学习语言的基础,我不打算做任何大的事情:P)。我的第一个问题是在互联网上找不到解决方案: 实体有一个主类: class entity { //something there };

如何在一个数组/容器中使用不同的对象? 我是C++初学者,做我的第一个2D游戏(只是为了学习语言的基础,我不打算做任何大的事情:P)。我的第一个问题是在互联网上找不到解决方案: 实体有一个主类: class entity { //something there };,c++,loops,entity,main,collision,c++11,C++,Loops,Entity,Main,Collision,C++11,以及一些具体怪物、玩家等的派生类 class zombie : public entity { //... }; class mutant : public entity ... class player : public entity ... 现在的问题是如何为所有类型的实体创建一个数组(或一些容器/任何东西)?我的意思是,如果所有怪物和玩家对象都来自“实体”类,例如,碰撞将很简单: std::vector<entity> entityTbl; entityTbl.push_

以及一些具体怪物、玩家等的派生类

class zombie : public entity
{
  //...
};
class mutant : public entity
...
class player : public entity
...
现在的问题是如何为所有类型的实体创建一个数组(或一些容器/任何东西)?我的意思是,如果所有怪物和玩家对象都来自“实体”类,例如,碰撞将很简单:

std::vector<entity> entityTbl;
entityTbl.push_back( entity(...) );
...
entityTbl.push_back( entity(...) );

for(int i=0;i<entityTbl.end();i++)
  for(int k=0;k<entityTbl.end();k++)
    entityTbl[i].collision(entityTbl[k]); //some collision function
std::vector entityTbl;
实体tbl.push_back(实体(…);
...
实体tbl.push_back(实体(…);

对于(int i=0;i您不能有抽象类的实例。请尝试以下操作,而不是像您的示例那样:

 std::vector<std::shared_ptr<entity> > entityTbl;
 entityTbl.push_back( new zombie(...) );     
 entityTbl.push_back( new mutant(...) );

尝试使用抽象类对象将出现错误,正如您在代码中尝试的那样。 您可以拥有一个指向抽象类的指针(在您的案例中是实体)。 指向基类的指针可以指向派生类。 例如:

class base {
public: virtual void func() = 0;
};

class derived : public virtual base {
    void func() override { std::cout << "\"base\" type pointer, but pointing to \"derived\"." << '\n'; }
};
int main()
{
    base *basep;
    basep = new derived;
    basep->func();
    system("PAUSE");
    return EXIT_SUCCESS;
}
有关更多信息:


祝你好运。

C++区分大小写。请使用
std::vector
或者更好的
std::vector
。但是你需要先修复许多其他错误才能使代码可编译。非常感谢!我没想到会这么简单。再次感谢你!
 for(std::std::vector<entity*> >::iterator it = entityTbl.begin(); 
     it != entityTbl.end();
     ++it) {
     delete *it;
 }
class base {
public: virtual void func() = 0;
};

class derived : public virtual base {
    void func() override { std::cout << "\"base\" type pointer, but pointing to \"derived\"." << '\n'; }
};
int main()
{
    base *basep;
    basep = new derived;
    basep->func();
    system("PAUSE");
    return EXIT_SUCCESS;
}
for (auto i = entityTbl.begin(); i != entityTbl.end(); i++)
    for (auto k = entityTbl.begin(); i != entityTbl.end(); k++)