简体   繁体   English

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

[英]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仅适用于多态类型,即具有虚函数表的structclass

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.

相关问题 有什么方法可以在投射到孩子时使用dynamic_cast吗? - Is There a way to use dynamic_cast When Casting to a Child? 将派生类转换为基类时,dynamic_cast失败 - dynamic_cast fails when cast a derived class to base class 将基础 class 转换为派生 class 时,dynamic_cast 失败 - dynamic_cast fails when cast a base class to derived class 是否可以从一个基类到另一个基类进行dynamic_cast? - Is it possible to dynamic_cast from one base class to another? 从不同基类的基指针转换为基类(最好没有dynamic_cast) - Cast to base class from base pointer from different base class (preferably without dynamic_cast) `dynamic_cast`从Base到Derived - `dynamic_cast` from Base to Derived 使用指向基本abstact类的指针访问子类成员,该类不能是dynamic_cast - Accessing child class members using pointer to a base abstact class, which can't be dynamic_cast 在 C++ 中使用 dynamic_cast 转换引用参数时出错 - Error when casting a reference parameter with dynamic_cast in C++ 将基类作为参数传递给虚函数时,避免使用dynamic_cast - Avoid dynamic_cast when passing base class as a param to a virtual function 当子对象存储在基本指针的向量上时,如何动态地从基类转换为子类 - How to dynamic cast from base to child class when the child is stored on a vector of base pointers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM