私は簡単なテストエンティティコンポーネントシステムを作成しています。私は基本的にいくつかの派生クラスを持つComponent
クラスを持っています。私はこれらのコンポーネントにいくつかのロジックを適用するいくつかのシステムを持っています。基本クラスから派生クラスポインタへのstatic_castが無効です
// 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*
)とのいずれかにI static_cast
両方の結果がでないときnullptr
、私はcc->input
ができないように、無効な値を取得する(つまり、キャストは成功しました)文字列から文字などに
を読んで、私はこのように、私のエンティティの工場に部品を配線:
void EntityFactory::wireUpPlayer(Entity* player)
{
player->addComponent(new HealthComponent());
player->addComponent(new ControlComponent());
player->addComponent(new PositionComponent());
}
とT
void Entity::addComponent(Component* component)
{
m_components.push_back(component);
}
これらのコンポーネントは、有効なメモリ・アドレスを有することが示されているので、私は問題がどこから来ているか分からない:次のようにaddComponentのための彼の実装です。
あなたは 'dynamic_cast'の機能を' static_cast'に帰属させています。これはうまく終了できません。 – IInspectable