[問題] RTTI typeid 的用法

看板C_and_CPP (C/C++)作者 (keep walking)時間19年前 (2006/02/15 16:34), 編輯推噓4(404)
留言8則, 2人參與, 最新討論串1/1
以下是我照著書上範例打的,還有output結果 使用Dev-c++編譯~ #include<iostream> #include<typeinfo> using namespace std; class BaseClass{ virtual void f() {}; //... }; class Derived1 : public BaseClass{ }; class Derived2 : public BaseClass{ }; int main() { double j; BaseClass *p, baseob; Derived1 ob1; Derived2 ob2; cout << "Typeid of j is: "; cout << typeid(j).name() << endl; p = &baseob; cout << "p is pointing to an object of type: "; cout << typeid(*p).name() << endl; p = &ob1; cout << "p is pointing to an object of type: "; cout << typeid(*p).name() << endl; p = &ob2; cout << "p is pointing to an object of type: "; cout << typeid(*p).name() << endl; system("pause"); return 0; } 結果: Typeid of j is: d p is pointing to an object of type: 9BaseClass p is pointing to an object of type: 8Derived1 p is pointing to an object of type: 8Derived2 問題: 請問為什麼output那邊三個type name之前會各有一個數字呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.116.245.211

02/15 16:48, , 1F
字串長度
02/15 16:48, 1F

02/15 16:48, , 2F
更正,class name 長度...
02/15 16:48, 2F

02/15 17:54, , 3F
謝謝~ 不知道是我這本書太舊還是有誤 他這個範例檔跑出來
02/15 17:54, 3F

02/15 17:56, , 4F
的結果沒有長度值...
02/15 17:56, 4F

02/15 18:42, , 5F
std::type_info::name() 是 compiler 實作,標準沒規定
02/15 18:42, 5F

02/15 18:43, , 6F
所以會跑出什麼字串是無法預期的(如果compiler不可預期)
02/15 18:43, 6F

02/15 18:44, , 7F
gcc 3.4 提供的名字老實說很難懂,僅供參考罷了
02/15 18:44, 7F

02/16 00:44, , 8F
原來如此~ 感謝您^^
02/16 00:44, 8F
文章代碼(AID): #13ykUmGT (C_and_CPP)
文章代碼(AID): #13ykUmGT (C_and_CPP)