C++ 尝试使用 dynamic_cast 时获取“源类型不是多态的”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15114093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:03:14  来源:igfitidea点击:

Getting "source type is not polymorphic" when trying to use dynamic_cast

c++c++11

提问by Andrew Tomazos

struct A {};

struct B : A {};

int main()
{
    A* a = new B();

    B* b = dynamic_cast<B*>(a);
}

gives:

给出:

cannot dynamic_cast 'a' (of type 'struct A*') to type 'struct B*' (source type is not polymorphic)

不能将“a”(类型为“struct A*”)动态转换为“struct B*”(源类型不是多态的)

How can I make Apolymorphic? I want to safely cast it to B.

我怎样才能使A多态?我想安全地将它投射到 B。

(One way is to add a dummy virtual function, but is there a better way?)

(一种方法是添加一个虚拟的虚函数,但有没有更好的方法?)

回答by juanchopanza

You need to make Apolymorphic, which you can do by adding a virtualdestructor or any virtual function:

您需要实现A多态,您可以通过添加virtual析构函数或任何虚函数来实现:

struct A {
  virtual ~A() = default;
};

or, before C++11,

或者,在 C++11 之前,

struct A {
  virtual ~A() {}
};

Note that a polymorphic type should have a virtual destructor anyway, if you intend to safely call delete on instances of a derived type via a pointer to the base.

请注意,如果您打算通过指向基类的指针安全地对派生类型的实例调用 delete,那么无论如何多态类型都应该具有虚拟析构函数。

回答by Luchian Grigore

You need at least a virtualfunction - typically, if no others are suitable, the destructor:

您至少需要一个virtual函数 - 通常,如果没有其他合适的函数,则析构函数:

struct A {
   virtual ~A() {}
}; 

回答by Andy Prowl

As your compiler says, your type Ais not polymorphic. You should add a virtualfunction to it. For instance, a virtualdestructor could be a good choice:

正如您的编译器所说,您的类型A不是多态的。你应该virtual给它添加一个函数。例如,virtual析构函数可能是一个不错的选择:

struct A { virtual ~A() { } };
//         ^^^^^^^ This makes A a polymorphic type

struct B : A {};

int main()
{
    A* a = new B();

    B* b = dynamic_cast<B*>(a); // Should work now
}