pre
class Base {
public:virtual void f1(){cout << "Base::f1()" << endl;}virtual void f2(){cout << "Base::f2()" << endl;}
};class Derive : public Base {
public:virtual void f1(){cout << "Derive::f1()" << endl;}virtual void f2(){cout << "Derive::f2()" << endl;}
};
指针
Base *pbase1 = new Derive();
Derive *pderive1 = dynamic_cast<Derive *>(pbase1);
pderive1->f1();
Derive &pderive11 = dynamic_cast<Derive &>(*pbase1);
pderive11.f1();
Base *pbase2 = new Base();
Derive *pderive2 = dynamic_cast<Derive *>(pbase2); if (pderive2 != nullptr) {pderive2->f1();pderive2->f2();
} else {cout << "pderive2 == nullptr" << endl;
}
Derive &pderive22 = dynamic_cast<Derive &>(*pbase2);
try {pderive22.f1();pderive22.f2();
} catch (exception &e) {cout << "pderive22 == nullptr" << endl;
}delete pbase1;
delete pbase2;
对象
Derive pbase1;
Derive &pderive1 = dynamic_cast<Derive &>(pbase1);
pderive1.f1(); Derive *pderive11 = dynamic_cast<Derive *>(&pbase1);
pderive11->f1();
Base pbase2;
Derive &pderive2 = dynamic_cast<Derive &>(pbase2);
Derive *pderive22 = dynamic_cast<Derive *>(&pbase2);