[英]dynamic_cast is failing when casting from base to child class
I have a struct我有一个结构
struct foo : public std::map<std::string, int>
{
};
and a child struct;和一个子结构;
struct bar : public foo
{
int another_member;
}
But I can't use bar* b = dynamic_cast<bar*>(f)
where f is a pointer to a foo.但是我不能使用bar* b = dynamic_cast<bar*>(f)
其中 f 是指向 foo 的指针。
Even if I refactor foo
to即使我将foo
重构为
struct foo
{
std::map<std::string, int> m;
};
I still have the problem.我仍然有问题。 I've played around with my RTTI settings to no avail.我玩过我的 RTTI 设置无济于事。 What on earth is going on?这到底是怎么回事?
The error is:错误是:
error C2683: 'dynamic_cast' : 'Credit::WaterfallSimulationResult' is not a polymorphic type错误 C2683:“dynamic_cast”:“Credit::WaterfallSimulationResult”不是多态类型
dynamic_cast
will only work on polymorphic types, that is struct
s or class
es that have a virtual function table. dynamic_cast
仅适用于多态类型,即具有虚函数表的struct
或class
。
The best thing to do is to introduce a virtual function into your base struct
, and the best function to introduce is the virtual destructor, which is arguably a good thing to do anyway:最好的办法是在你的基础struct
引入一个虚函数,而最好的引入函数是虚析构函数,这可以说是一件好事:
struct foo
{
std::map<std::string, int> m;
virtual ~foo(){};
};
Note that this forces you to use your "refactored" form of foo
: STL containers are not designed to be used as base classes.请注意,这会强制您使用“重构”形式的foo
:STL 容器并非设计为用作基类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.