这个全局函数或者叫库函数利用RTTI来转换指针或引用的类型,注意转换指针的时候不会抛异常,只有在转引用的时候才会抛异常:
#include <iostream> using namespace std; class People { public: People() { cout << "People constructed" << endl; } virtual void speak() = 0; }; class Man:public People { public: void speak() { cout << "A man speaks" << endl; } void fight() { cout << "A man fights" << endl; } }; class Woman:public People { private: Man son; int cookTimes; public: void speak() { cout << "A woman speaks" << endl; } void cook() { cout << "A woman cooks" << endl; cookTimes++; } Man getSon() { cout << "A woman's son:" << endl; return son; } }; ///////////////////////////SubMain////////////////////////////////// int main(int argc, char *argv[]) { People *p = new Man(); p->speak(); Man *m = dynamic_cast<Man *>(p); m->fight(); Man *m2 = (Man *)p; m2->fight(); try { Woman *w = dynamic_cast<Woman *>(p); if (w != NULL) { w->cook(); w->getSon().speak(); } } catch(bad_cast &e) { // 指针转换不会抛异常 cout << "bad_cast exception" << endl; } cout << "-----------------" << endl; try { Woman w = dynamic_cast<Woman &>(*p); w.cook(); w.getSon().speak(); } catch(bad_cast &e) { cout << "bad_cast exception" << endl; } delete p; system("pause"); return 0; } ///////////////////////////End Sub////////////////////////////////// /************************************************************************/ /* output: People constructed A man speaks A man fights A man fights ----------------- bad_cast exception */ /************************************************************************/