C++ primer
中看到这个dynamic cast
, 有点搞不太懂. 这个dynamic cast
的作用到底是干嘛? 如果说一个父类指针中实际指向一个子类的话, 如果用这个指针调用一个虚函数, 就算没有dynamic-cast
也会发生动态绑定吧? 如果用这个指针调用一个子类独有的函数, 那么这里应该用static cast
, 好像和dynamic cast
也没什么关系? 那就不懂了, dynamic cast
到底有什么用...
按照1L的回复我写了如下代码 :
//p.h
class P{
};
//s.h
#include "p.h"
class S : public P{
};
//main.cpp
#include <iostream>
#include "s.h"
int main(){
//std::shared_ptr<P> x(new S);
//std::shared_ptr<S> y = std::dynamic_pointer_cast<S>(x);
P* x = new S;
S* y = dynamic_cast<S*>(x);
}
结果报错 :
main.cpp:8:12: error: 'P' is not polymorphic
S* y = dynamic_cast<S*>(x);
^ ~
1 error generated.
dynamic_cast is typically used for down-cast check. e.g.
Thank you for the invitation.
Someone has already answered it well before, so I won’t go into details about the usage of
dynamic_cast
here.Here we mainly talk about why
dynamic_cast
should be used. The previous answer is that it is safer.Also, if you need to convert between different base class pointers pointing to the same object, using
dynamic_cast
can ensure the correctness of the conversion.There is also a pointer of the base class type, which can point to objects of different subclasses. However, pointers of two subclass types cannot point to each other's objects. If you convert, an error will occur. At this time, you can use
dynamic_cast
to determine which subclass object the base class pointer points to at runtime.Give an example. http://ideone.com/oUgVpo
dynamic_cast has the function of type checking, and a bad_cast exception will be thrown if it fails. Safer than static_cast, static_cast is forced to transfer directly without any check
After repeated experiments, I found that I only need to add a virtual function to the parent class, or set the destructor to a virtual function, but I don’t know why this happens...
The simplest example:
http://stackoverflow.com/ques...
The dynamic_cast conversion is based on the type_info in front of the virtual table for conversion. Only classes containing virtual functions can use dynamic_cast.
And the above type_info is generated by the compiler during compilation, so if type_info is not found during compilation, an error will be reported.