好吧,为了说明我遇到的问题,我将显示一些(伪)代码。无法返回包含派生指针的向量
可以说我有以下型号:
class Animal : public GameObject;
class Player : public GameObject;
class GameObject : public ObjectInterface;
class ObjectInterface
{
public:
virtual ~ObjectInterface() = default;
virtual vec3 GetPosition() = 0;
}
现在我还保存一些“对象上下文”,它拥有一定的游戏对象的集合。
class ContextObject
{
// they implement ObjectInterface
vector<shared_ptr<Animal>> animals;
vector<shared_ptr<Player>> players;
}
现在我有一个TargetSelector
类,它只有在ObjectInterface
直接作用。
class TargetSelector
{
// this is somehow not possible, although `animals` are a subclass of `ObjectInterface`
vector<shared_ptr<Model::ObjectInterface>>& GetAvailableTargets()
{
return context->animals; // context is some `ObjectContext`
}
}
我希望上面的代码工作,因为一个Animal
是类型ObjectInterface
的。但相反,我得到一个错误,说它不能从vector<shared_ptr<Animal>>
转换为vector<shared_ptr<ObjectInterface>>
。这甚至假设工作?
有人可以解释我为什么我不能做这种多态性,如果可能的话,一个很好的解决方案,所以我可以做到这一点。
谢谢,任何帮助表示赞赏!
'shared_ptr '和'shared_ptr '是不同的类型。您可以将一个转换为另一个,但不能将它们别名。如果你想创建一个'vector >',你需要填写'shared_ptr '等副本。 –
也许你应该在所有情况下都存储'shared_ptr',动物'如果需要可以投入使用 –