[英]dynamic_cast is failing when casting from base to child class
我有一个结构
struct foo : public std::map<std::string, int>
{
};
和一个子结构;
struct bar : public foo
{
int another_member;
}
但是我不能使用bar* b = dynamic_cast<bar*>(f)
其中 f 是指向 foo 的指针。
即使我将foo
重构为
struct foo
{
std::map<std::string, int> m;
};
我仍然有问题。 我玩过我的 RTTI 设置无济于事。 这到底是怎么回事?
错误是:
错误 C2683:“dynamic_cast”:“Credit::WaterfallSimulationResult”不是多态类型
dynamic_cast
仅适用于多态类型,即具有虚函数表的struct
或class
。
最好的办法是在你的基础struct
引入一个虚函数,而最好的引入函数是虚析构函数,这可以说是一件好事:
struct foo
{
std::map<std::string, int> m;
virtual ~foo(){};
};
请注意,这会强制您使用“重构”形式的foo
:STL 容器并非设计为用作基类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.