【问题标题】:C++ Objected building function returning Base class type [duplicate]C ++对象构建函数返回基类类型[重复]
【发布时间】:2019-08-11 17:07:49
【问题描述】:

我已经离开 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"));



}

是说做动态演员吗?对于这种情况,有什么更好的方法?谢谢

【问题讨论】:

  • 我的建议是不要这样做。而是研究虚拟函数并将其作为几乎最后的手段。

标签: c++ polymorphism


【解决方案1】:

这是相当标准的,请参阅:covariant return type

【讨论】:

    猜你喜欢
    • 2012-10-28
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多