关于C++中的dynamic cast的使用
本文介绍了关于C++中的dynamic cast的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
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.
class Base{
// ....
// Base must be polymorphic!!! (has virtual members)
virtual void foo();
};
class Derive: public Base{
virtual void foo() override {
cout<<"Derive::foo()"<<endl;
}
void derive_only() {
cout<<"this method only exists for derive type\n";
}
};
Base* pDerive = new Derive();
Derive* pd;
if((pd = dynamic_cast<Derive*>(pDerive)){
//downcast successful
pd->derive_only(); // prints "derive only method"
}else{
//the pDerive is not Derive type
}
这篇关于关于C++中的dynamic cast的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文