C++ 如何返回派生类型的对象而不转换回基类类型?

C++ 如何返回派生类型的对象而不转换回基类类型?,c++,polymorphism,type-conversion,components,C++,Polymorphism,Type Conversion,Components,首先,我真的很抱歉这个标题,但我不知道如何恰当地表达我的问题。不管怎样,我只是在用C++和AlelGo 5来搞游戏,只是用更复杂的技术来练习。现在我正在尝试使用实体和组件,但遇到了一个障碍 this->entity = new Entity(); this->entity->addComponent(new ComponentTest()); // How I currently access components ComponentTest *c = (Componen

首先,我真的很抱歉这个标题,但我不知道如何恰当地表达我的问题。不管怎样,我只是在用C++和AlelGo 5来搞游戏,只是用更复杂的技术来练习。现在我正在尝试使用实体和组件,但遇到了一个障碍

this->entity = new Entity();

this->entity->addComponent(new ComponentTest());

// How I currently access components

ComponentTest *c = (ComponentTest*)this->entity->getComponent("test");
c->setVariable(10);

// This would be cool

this->entity->getComponent("test")->setVariable(10);

// This would be completely rad

this->entity["test"]->setVariable(10);
问题是Entity::getComponent返回一个指向组件的指针,因此我必须显式地将其转换回ComponentTest,以便能够使用其方法ComponentTest::setVariable

我只是想知道是否有办法使用我提到的另外两种访问方式。我也愿意接受一些关于修改代码的建议,以便更容易地访问实体的组件


tl;dr:太懒了,无法显式转换组件。是否可以通过其他两种方式访问组件?

您可以在实体中定义模板函数,如下所示:

    template<typename T>
    T* getComponent(const std::string &componentName)
    {
        Component *component = getComponent(componentName);
        return dynamic_cast<T*>(component);
    }
模板
T*getComponent(常量std::string和componentName)
{
Component*Component=getComponent(componentName);
返回动态_-cast(组件);
}

并像前面提到的@Jarod42那样调用它。

您可以在实体中定义一个模板函数,如下所示:

    template<typename T>
    T* getComponent(const std::string &componentName)
    {
        Component *component = getComponent(componentName);
        return dynamic_cast<T*>(component);
    }
模板
T*getComponent(常量std::string和componentName)
{
Component*Component=getComponent(componentName);
返回动态_-cast(组件);
}

并像前面提到的@Jarod42那样调用它。

类似这样的东西怎么样:
this->entity->getComponent(“test”)->setVariable(10)Base
Derived
etcHow,比如:
this->entity->getComponent(“test”)->setVariable(10)Base
派生的