简体   繁体   English

C ++ Polymorphism - 继承类的映射

[英]C++ Polymorphism - Map of inherited classes

I have a MovementSystem class which inherits from a System class. 我有一个继承自System类的MovementSystem类。 Later I will have a number of xxxSystem classes so I will store the instances of xxxSystem (there is only one instance per system) in a map this way: 稍后我会有一些xxxSystem类,所以我将以这种方式在地图中存储xxxSystem的实例(每个系统只有一个实例):

enum
{
    MOVEMENT_SYSTEM
};

std::map<int,std::unique_ptr<System>> systems;
systems[MOVEMENT_SYSTEM] = std::unique_ptr<System>(new MovementSystem());

m_entityManager.loadSystems(&systems);

The last line is there because I need my class EntityManager to have access to all the systems. 最后一行是因为我需要我的类EntityManager来访问所有系统。

Therefore I have this method: 因此我有这个方法:

std::map<int,std::unique_ptr<System>> *m_systems; // this line is in the header

void EntityManager::loadSystems(std::map<int,std::unique_ptr<System>> *systems)
{
    m_systems = systems;
}

And finally in an other method of EntityManager I try to access the systems I have sent to the class this way: 最后在EntityManager的另一个方法中,我尝试以这种方式访问​​我发送给类的系统:

std::unique_ptr<MovementSystem> mvt = (*m_systems)[MOVEMENT_SYSTEM];
mvt->update(dt);

But I get this error: 但我得到这个错误:

conversion from 'std::map<int, std::unique_ptr<System> >::mapped_type {aka std::unique_ptr<System>}' to non-scalar type 'std::unique_ptr<MovementSystem>' requested

How can I fix this and get the last line to call the update method from MovementSystem ? 我该如何解决这个问题并获取最后一行来从MovementSystem调用更新方法?

std::unique_ptr<MovementSystem> mvt = *m_systems[MOVEMENT_SYSTEM];

There are two problems with this line. 这条线有两个问题。 One, operator precedence is such that it will get interpreted as this: 一,运算符优先级是这样的,它将被解释为:

*(m_systems[MOVEMENT_SYSTEM])

This means it will apply pointer arithmetic to the pointer m_systems (accessing the MOVEMENT-SYSTEM th element in an "array" pointed to by m_systems ) and then apply * to that map, which is nonsense. 这意味着它将应用于指针运算指针m_systems (访问MOVEMENT-SYSTEM个要素中的“阵列”所指向的m_systems ),然后应用*到地图,这是无义。 What you wanted was this: 你想要的是这个:

(*m_systems)[MOVEMENT_SYSTEM]

The second problem is that you're trying to copy a unique pointer. 第二个问题是你试图复制一个唯一的指针。 Which is precisely what unique pointers are designed to prevent. 这正是设计用于防止的唯一指针。

What you probably want is simply get the pointer, and cast it accordingly: 您可能想要的只是获取指针,并相应地投射它:

MovementSystem *mvt = static_cast<MovementSystem*>((*m_systems)[MOVEMENT_SYSTEM].get());

Or, even better because it gets rid of unnecessary pointers: 或者,甚至更好,因为它摆脱了不必要的指针:

auto &systems = *m_systems;
auto &mvt = static_cast<MovementSystem&>(*systems[MOVEMENT_SYSTEM]);
mvt.update(dt);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM