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.