如何在不转换回基类类型的情况下返回派生类型的对象?
How to return an object in its derived type without converting back to base class type?
首先,我真的很抱歉标题,但我不知道如何正确表达我的问题。无论如何,我弄乱了C++和Allegro 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);
}
并像@Jarod42提到的那样称呼它。
相关文章:
- 如何在模板参数中分离函数类型返回类型和参数
- 为什么要为指针返回类型返回一系列字符?
- 有没有办法根据运行时值的类型返回 constexpr 对象
- 从弱指针返回类型返回共享指针
- 无法为unique_ptr返回类型返回 nullptr
- 为什么双重类型返回无穷大
- std::is_arithmetic 为通用 lambda 中的 int 类型返回 false:未定义的行为?
- C 策略设计具有可变类型返回值
- 根据类型返回一个值
- 在C++中,将double转换为long的类型返回了不正确的值
- 作为宏参数的安装类型返回错误:字符串常量之前的预期非限定 id
- 具有引用类型返回的函数
- C++ 如何使模板<T>f() 为整数 T 返回 -1,为指针类型返回 nullptr
- C++模板:按类型返回值
- 以Integer返回类型返回浮点值
- 使用 C++14 的自动功能类型返回扣除代替 std::common_type 是否始终安全?
- 为什么允许新运算符向每个指针类型返回*void
- 适当的函数返回类型返回日期时间
- c++中布尔类型返回函数的默认返回值
- 在c#中使用非托管c++代码对所有double类型返回0