问题描述
我正在创建一个简单的测试实体组件系统.我有一个带有几个派生类的基本Component
类.然后,我有几个将逻辑应用于这些组件的系统.
I am creating a simple test entity-component system. I have a base Component
class with several derived classes. I then have several systems that apply some logic to these components.
// 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...
}
}
}
当我从基数Component*
到派生组件(PositionComponent*
或ControlComponent*
)中的任何一个,并且两个结果都不都是nullptr
时(即强制转换成功),我得到无效值,例如cc->input
无法从字符串等中读取字符.
When I static_cast
from base Component*
to either of the derived components (PositionComponent*
or ControlComponent*
) and when both results are not nullptr
(i.e the cast was successful), I get invalid values, like cc->input
not being able to read characters from string etc.
我将实体工厂中的组件连接起来,像这样:
I wire up the components in my entity factory, like this:
void EntityFactory::wireUpPlayer(Entity* player)
{
player->addComponent(new HealthComponent());
player->addComponent(new ControlComponent());
player->addComponent(new PositionComponent());
}
addComponent的实现如下:
And the implementation for addComponent is as follows:
void Entity::addComponent(Component* component)
{
m_components.push_back(component);
}
这些组件显示为具有有效的内存地址,所以我不确定问题出在哪里.
These components are shown to have valid memory addresses, so I'm not sure where the issue is coming from.
推荐答案
static_cast
在运行时不检查有效性;如果强制转换已编译,则它将在运行时假定转换正常.如果您不强制转换为空指针,则static_cast
的结果将不是空指针.要获得检查的强制转换,您需要dynamic_cast
,而这又需要将指针转换为指向多态类型,即具有至少一个虚函数的类型.这意味着将Component
更改为至少具有一个虚函数.
static_cast
does not check validity at runtime; if the cast compiled, it assumes at runtime that the conversion is okay. If you aren't casting a null pointer, the result of a static_cast
will not be a null pointer. To get a checked cast you need dynamic_cast
and that, in turn, requires the pointer being converted to point to a polymorphic type, i.e., one that has at least one virtual function. That means changing Component
to have at least one virtual function.
这篇关于从基类指针到派生类指针的static_cast无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!