#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
最新推荐文章于 2022-04-05 15:39:37 发布