我有一个基类、2 个派生类和一个 entitymanager 类,它有一个指向派生对象的基指针容器。我在基类中有一个虚拟克隆方法来处理派生类中的复制构造函数,但是我在重载赋值运算符和防止切片方面遇到了麻烦,有人可以帮忙,也许可以回顾一下我是如何处理的entitymanager 复制构造函数?我觉得还可以
class System
{
public:
virtual System* clone()=0;
};
class projectile :public System
{
public:
projectile* clone()
{
return new projectile(*this);
}
};
class player : public System
{
public:
player* clone()
{
return new player(*this);
}
};
class EntityManager
{
private:
vector<System*> theEntities;
public:
EntityManager(){}
EntityManager(EntityManager& other)
{
for (size_t i=0;i<other.theEntities.size();i++)
theEntities.push_back(other.theEntities[i]->clone());
}
void init()
{
projectile* aProjectile = new projectile;
player* aPlayer = new player;
theEntities.push_back(aProjectile);
theEntities.push_back(aPlayer);
}
};
int main (int argc, char * const argv[])
{
EntityManager originalManager;
originalManager.init();
EntityManager copyManager(originalManager);
return 0;
}