从基类转换为子类时,dynamic_cast失败

P45*_*ent -4 c++ dynamic-cast

我有一个结构

struct foo : public std::map<std::string, int>
{
};
Run Code Online (Sandbox Code Playgroud)

和儿童结构;

struct bar : public foo
{
    int another_member;
}
Run Code Online (Sandbox Code Playgroud)

但我不能使用bar* b = dynamic_cast<bar*>(f)f是指向foo的指针.

即使我重构foo

struct foo
{
     std::map<std::string, int> m;
};
Run Code Online (Sandbox Code Playgroud)

我还有问题.我玩过我的RTTI设置无济于事.到底是怎么回事?

错误是:

错误C2683:'dynamic_cast':'Credit :: WaterfallSimulationResult'不是多态类型

Bat*_*eba 8

dynamic_cast仅适用于具有虚函数表的多态类型,即structs或classes.

最好的办法是在你的基础中引入一个虚函数struct,引入的最好的函数是虚析构函数,无论如何这可能是件好事:

struct foo
{
     std::map<std::string, int> m;
     virtual ~foo(){};
};
Run Code Online (Sandbox Code Playgroud)

请注意,这会强制您使用"重构"形式foo:STL容器不能用作基类.