我正在创建一个简单的测试实体组件系统。我有一个带有几个派生类的Component
基类。然后,我有几个将某些逻辑应用于这些组件的系统。
// Component.h
// ------------
class Component
{
public:
Component();
~Component();
}
// ControlComponent.h
// -------------------
#include <string>
#include "Component.h"
class ControlComponent : public Component
{
public:
std::string input = ""; // store simple input instruction
ControlComponent();
~ControlComponent();
};
// ControlSystem.cpp
void ControlSystem::update(Entity* entity)
{
vector<Component*>* components = entity->getComponents();
for (Component* component : *components)
{
PositionComponent* pc = static_cast<PositionComponent*>(component);
ControlComponent* cc = static_cast<ControlComponent*>(component);
if (pc != nullptr && cc != nullptr)
{
std::cout << "Which direction would you like to go?" << std::endl;
std::string input;
std::cin >> input;
cc->input = input; // application breaks here
// Apply some logic...
}
}
}
当我从基本
static_cast
到另一个派生组件(Component*
或PositionComponent*
)进行ControlComponent*
编码时,并且当两个结果都不都是nullptr
时(即强制转换成功),我得到了无效值,例如cc->input
无法从字符串等中读取字符。我将实体工厂中的组件连接起来,如下所示:
void EntityFactory::wireUpPlayer(Entity* player)
{
player->addComponent(new HealthComponent());
player->addComponent(new ControlComponent());
player->addComponent(new PositionComponent());
}
并且addComponent的实现如下:
void Entity::addComponent(Component* component)
{
m_components.push_back(component);
}
这些组件显示为具有有效的内存地址,因此我不确定问题出在哪里。
最佳答案
static_cast
在运行时不检查有效性;如果强制转换已编译,则它将在运行时假定转换正常。如果您不强制转换为空指针,则static_cast
的结果将不会为空指针。要获得选中的类型转换,您需要dynamic_cast
,这又需要将指针转换为指向多态类型,即具有至少一个虚函数的指针。这意味着将Component
更改为至少具有一个虚函数。
关于c++ - 从基类指针到派生类指针的static_cast无效,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42011458/