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
Getting "source type is not polymorphic" when trying to use dynamic_cast
提问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)
How can I make A
polymorphic? 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 A
polymorphic, which you can do by adding a virtual
destructor 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 virtual
function - typically, if no others are suitable, the destructor:
您至少需要一个virtual
函数 - 通常,如果没有其他合适的函数,则析构函数:
struct A {
virtual ~A() {}
};
回答by Andy Prowl
As your compiler says, your type A
is not polymorphic. You should add a virtual
function to it. For instance, a virtual
destructor 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
}