gpt4 book ai didi

C++ 对象构建函数返回基类类型

转载 作者:太空宇宙 更新时间:2023-11-04 12:38:49 24 4
gpt4 key购买 nike

<分区>

我很久没接触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"));



}

是说要进行动态转换吗?对于这种情况,更好的方法是什么?谢谢

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com