我已经远离c ++很久了,所以很生锈,但是我应该能够做到这一点吗?我想构建对象,然后将其转换为更专业的派生类。
#pragma once
class GameObject
{
public:
GameObject();
virtual ~GameObject();
int x, y;
}
class PlayerObject : Public GameObject
{
PlayerObject();
virtual ~PlayerObject();
int x, y;
string name;
};
class Game
{
unique_ptr<GameObject> randomObject;
unique_ptr<PlayerObject> player;
}
#########################
unique_ptr<GameObject> GameObjectManager::buildGameObject(string gameObjectId)
{
unique_ptr<GameObject> gameObject;
gameObject = make_unique< GameObject>();
return gameObject;
}
##################################
int main(int argc, char *args[])
{
unique_ptr<GameObject> rock = gameObjectManager.buildGameObject("ROCK"));
unique_ptr<PlayerObject> playerObject = dynamic_cast<unique_ptr<PlayerObject>>(Game::gameObjectManager.buildGameObject("PLAYER"));
}
是否说要这样做动态转换。遇到这种情况,哪种更好的方法是什么?谢谢