精華區beta Programming 關於我們 聯絡資訊
==> 在 william.bbs@cis.nctu.edu.tw (何陋居主) 的文章中提到: : ==> 在 "Knight" <knight@handel.mba.ntu.edu.tw> 的文章中提到: : > class base {}; : > class derived : public base {}; : [deleted] : > 根據help的說法,應該 t2 的 name() 是 derived 才對啊! : > 結果兩者分別為: : > class base * : > class base : > 偵測不出執行時期的型別,RTTI還有什麼用勒? : The C++ Programming Language 3/e 第 15.4 節有言: : C++ 的 RTTI 機制(尤其是 dynamic_cast、typeid)要正常運作, : 運算元就必須是個 polymorphic type(多型型別)。 : 所以, 只要你把上面的程式小改一個地方: : class base { virtual void f() {} }; // 讓它變成多型型別 : 就能得到你想要的效果了。 想問一下,那為什麼 C++ Polymorphic 機制,也可以藉由 C++ 的 RTTI (typeid) 來模擬,而不需要將它變成多型型 別呢?舉例如下: CShape sh; CCircle ci; CTriangle tr; CCone co; CShape *sp[4] = {&tr, &ci, &co, &sh}; for (int i=0; i<4; i++) sp[i]->Draw(); 其中 Draw() 成員函式均被各衍生類別改寫,但基底類別的 Draw() 並非 virtual functioin,但其定義如下: void CShape::Draw() { if (typeid(*this) == typeid(CTriangle)) ((CTriangle*)this)->Draw(); else if (typeid(*this) == typeid(CCone)) ((CCone*)this)->Draw(); else if (typeid(*this) == typeid(CCircle)) ((CCircle*)this)->Draw(); else if (typeid(*this) == typeid(CShape)) ((CShape*)this)->Draw(); }