dynamic_cast
/*
*对指针进行dynamic_cast,失败返回null,成功返回正常cast后的对象指针;
*对引用进行dynamic_cast,失败抛出一个异常,成功返回正常cast后的对象引用
*/
#include <iostream>
#include <typeinfo>
class Base {
virtual int test() { #必须为virtual,不然编译报错
return 0;
}
};
class Derived : public Base {
virtual int test() {
return 1;
}
};
int main() {
Base b1;
Derived d1;
//case 1:
Base *b1 = new Base;
if (Derived *d1 = dynamic_cast<Derived*> (b1)) { //fail
std::cout << "cast b1* successful." << std::endl;
}
//case 2:
Base *b2 = new Derived;
if (Derived *d2 = dynamic_cast<Derived*> (b2)) { //success
std::cout << "cast b2* successful." << std::endl;
d2->test();
}
//case 3
try{
Derived &d1 = dynamic_cast<Derived&> (*b1); //fail
} catch(std::bad_cast) {
std::cout << "cast b1& successful." << std::endl;
}
//case 4
try{
Derived &d2 = dynamic_cast<Derived&> (*b2); //success
d2.test();
} catch(std::bad_cast) {
std::cout << "cast b2& successful." << std::endl;
}
return 0;
}