通过基类型

时间:2017-06-14 13:54:30

标签: c++ shared-ptr

所以我有4个类定义:

class Body
{//not important};

class CelestialBody: public Body
{//not important}

class Star: public CelestialBody
{//not important}

class Starship: public Body
{//not important}

然后我定义了这些对象的shared_ptrs向量:

vector<shared_ptr<Starship> > starships;
vector<shared_ptr<CelestialBody> > planetoids;
vector<shared_ptr<Star> > stars;
vector<Body*> bodies;

然后我用对象填充:

for(int i=0; i<1; ++i)
{
    starships.push_back(shared_ptr<Starship>(new Starship));
    bodies.push_back(starships[starships.size()-1].get());
}
for(int i=0; i<totalOfBodies; ++i)
{
    planetoids.push_back(shared_ptr<CelestialBody>(new CelestialBody));
    bodies.push_back(planetoids[planetoids.size()-1].get());
}
for(int i=0; i<0; ++i)
{
    stars.push_back(shared_ptr<Star>(new Star));
    bodies.push_back(stars[stars.size()-1].get());
}

这一切都按照我想要的方式运作:我有一个矢量可以到达所有的身体,我有一个向量来触及所有的小行星,所有的星星和所有星舰。但现在我想从bodies向量和starships向量中删除星舰,但我只知道bodies向量中的索引:

if(bodies[j]->Type() == starshipType) 
{
    starships.erase(find(starships.begin(), starships.end(), bodies[j]));
    //error:  no match for ‘operator==’ (operand types are ‘std::shared_ptr<Starship>’ and ‘Body* const’)

}
bodies.erase(bodies.begin() + j);

我理解它产生的错误,但我不知道该怎么做。

Bo基本上我想要一个包含所有Bodies对象的大向量(所以也是孩子们)和几个包含不同类型对象的小对象,但是我仍然希望保留从大向量中删除对象的可能性特定的载体。

编辑:

好的,基本上我错过了将bodies定义为vector<shared_ptr<Body> >。 但是找到的部分不起作用:

starships.erase(find(starships.begin(), starships.end(), bodies[j]));

我在shared_ptr<Body>的向量中搜索shared_ptr<Starship>,它始终返回向量的结尾。如何在对象切片版本的同时搜索派生类的对象?

另一个编辑:

感谢您的快速回复。我认为std::find_if()以及id系统将适合我。

0 个答案:

没有答案
相关问题