#include<iostream>
#include<string>
#include<vector>
#include<map>
using namespace std;
class B
{
public:
void method() { cout << "from B"<<endl; }
virtual void print() { cout << "print from B"; }
};
class A :public B
{
public:
void method() { cout << "from A" << endl; }
void print() { cout << "print from A"<<endl; }
};
int main(int argn, char** args)
{
B b;
b.method();
A a;
a.method();
A* ap = new A();
ap->method();
auto bp = dynamic_cast<B*>(ap);
bp->method();
// if B hasn't a virtual method,below cast cannot success
auto app = dynamic_cast<A*>(bp);
app->print();
auto bpp = new B();
//this below cast will not success, the "appp" will be nullptr
auto appp = dynamic_cast<A*> (bpp);
appp->print();
// when use dynamic_cast<A*> .success return A* .failure return nullptr
// when use dynamic_cast<A&> .success return A& .failuer will throw a "bad_cast" exception
return 0;
}
c++ dynamic_cast
最新推荐文章于 2024-08-15 15:21:30 发布
本文通过C++代码示例详细介绍了基类与派生类之间的动态类型转换,包括dynamic_cast操作符的使用及其成功与失败的情况。演示了如何在运行时确定对象的真实类型,并展示了多态性在C++中的应用。
1309

被折叠的 条评论
为什么被折叠?



