close

在dynamic_cast中(behind this post) , 我們提到 , 若derived class inherit virtual function from base class , 

若同樣以base class做為引數傳入 , 在C++中是沒辦法直接知道這個argument的實際type. (RTTI , run time type information)

(因為function overloading是在compile time時靜態決定)

所以若想要知道這個argument的type是甚麼 , 通常有三種方法:

1. 用double dispatching.

2. 用dynamic_cast

3. 就是我們這裡所要提到的: typeid

 

#include <iostream> 
#include <typeinfo>
using namespace std;

class Base {
public:
virtual void foo() {
cout << "Base" << endl;
}
};

class Derived1 : public Base {
public:
void foo() {
cout << "Derived1" << endl;
}
};

class Derived2 : public Base {
public:
void foo() {
cout << "Derived2" << endl;
}
};

int main() {
Base *ptr; // 基底類別指標
Base base;
Derived1 derived1;
Derived2 derived2;

ptr = &base;
cout << "ptr 指向 "
<< typeid(*ptr).name()
<< endl;

ptr = &derived1;
cout << "ptr 指向 "
<< typeid(*ptr).name()
<< endl;

ptr = &derived2;
cout << "ptr 指向 "
<< typeid(*ptr).name()
<< endl;

return 0;
}
 
ref : http://caterpillar.onlyfun.net/Gossip/CppGossip/RTTI.html
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 JerryCheng 的頭像
    JerryCheng

    KwCheng's blog

    JerryCheng 發表在 痞客邦 留言(0) 人氣()