1. 程式人生 > 程式設計 >詳解c++中的型別識別

詳解c++中的型別識別

1、型別識別的相關概念

(1)型別識別的作用

  型別識別是面向物件中引入的一個新概念,主要用來判斷賦值相容性原則中的型別問題,即此時的資料型別到底是基類型別還是派生類型別?

  當基類指標指向子類物件 或者基類引用成為子類物件的別名 時,就需要使用型別識別;

Base *p = new Derived();
Base &r = *p

對於上面的語句,我們可以這樣認識,指標p是Base型別,但是P 又指向了一個新的Derived型別,此時很難判斷指標P 的資料型別;同理,引用r 本來作為父類的別名而存在,但由於賦值相容性,引用r也可以作為子類的別名,同樣此時 引用 r 的資料型別也不能確定;

  注:1)由之前所學知識,若沒有虛擬函式重寫,編譯器為了安全起見,會將指標p 當作 Base 型別;(編譯期間)    

    2)若有虛擬函式重寫,就會發生動態多型特性,此時就會根據指標p 所指向的具體資料型別來確定指標p 的資料型別。(執行期間)

(2)型別識別的分類

詳解c++中的型別識別

  1)靜態型別:變數(物件)自身的型別;在編譯階段就能確定所使用變數的資料型別。

  2)動態型別:指標(引用)所指向物件的實際型別;在執行階段根據指標所指向的具體資料型別來確定所使用的資料型別。

詳解c++中的型別識別

    Base *b 所指向的實際物件無法確定,若指標b 指向的是子類物件,則程式正常執行;若指標b 指向的是父類物件,則程式有可能出現 Bug;

    注:在 g++ 編譯器下上述情況均可正常執行,但後者不建議使用;

  在賦值相容原則中,基類指標是否可以強制型別轉換為子類指標取決於動態型別;(很重要!!!)--- 只有動態型別是子類物件才能進行合法轉換

2、如何得到動態型別

(1)利用多型

  1)必須從基類開始提供型別虛擬函式;

  2)所有的派生類都必須重寫型別虛擬函式;

  3)每個派生類的型別 ID必須唯一;

   結果:呼叫型別虛擬函式就可以知道當前的物件究竟是什麼型別,這樣就可以得到動態型別,達到動態型別識別效果;

利用型別虛擬函式實現型別識別

 #include <iostream>
 #include <string>
 
 using namespace std;
 
 class Base
 {
 public:
   enum { ID = 0 };
   
   virtual int type() // 型別虛擬函式
   {
     return ID;
   }
 };
 
 class Derived : public Base
 {
 public:
   enum { ID = 1 };
   
   int type()
   {
     return ID;
   }
   
   void print()
   {
     cout << "I'm a Derived. " << endl;
   }
 };
 
 class Child : public Base
 {
 public:
   enum { ID = 2 };
   
   int type()
   {
     return ID;
   }
 };
 
 void test(Base* pb)
 {
   if( pb->type() == Child::ID )
   {
     Child* pc = static_cast<Child*>(pb);
     //Child* pc = dynamic_cast<Child*>(pb);  // 同上
     
     cout << "& = " << pc << endl;
     cout << "I'm a Child. " << endl;
   }
   
   if( pb->type() == Derived::ID )
   {
     Derived* pd = static_cast<Derived*>(pb);
     //Derived* pd = dynamic_cast<Derived*>(pb); // 同上
     
     cout << "& = " << pd << endl;
     pd->print();
   }
   
   if( pb->type() == Base::ID )
   {
     cout << "& = " << pb << endl;
     cout << "I'm a Base. " << endl;
   }
 }
 
 int main(int argc,char *argv[])
 {
   Base b;
   Derived d;
   Child c;
   
   test(&b);
   test(&d);
   test(&c);
   
   return 0;
 }
 /**
 * 執行結果:
 * & = 0x7ffccf0dd850
 * I'm a Base. 
 * & = 0x7ffccf0dd860
 * I'm a Derived.
 * & = 0x7ffccf0dd870
 * I'm a Child.
 */

(2)利用 dynamic_cast

  1)dynamic_cast這個關鍵字如果要轉換的實際型別和指定的型別不一樣,則會返回NULL。例如當指定型別為子類物件時,如果父類指標的動態型別是這個子類物件時,轉換成功,而動態型別是父類物件或者其他子類物件時,轉換失敗;

  2)dynamic_cast 要求使用的目標物件型別必須是多型,即:所在類族至少有一個虛擬函式;

  3)只能用於指標和引用之間的轉換

    1.用於指標轉換時,轉換失敗,返回空指標;

    2.用於引用轉換時,轉換失敗,將引發 bad_cast異常。

 #include <iostream>
 #include <string>
 
 using namespace std;
 
 class Base
 {
 public:
   virtual ~Base()
   {
   
   }
 };
 
 class Derived : public Base
 {
 public:  
   void print()
   {
     cout << "I'm a Derived. " << endl;
   }
 };
 
 class Child : public Base
 {
 
 };
 
 void test(Base* pb)
 {
   // dynamic_cast 只能確定最終的轉化結果,無法獲取動態型別的原型
   Derived* pd = dynamic_cast<Derived*>(pb);
   
   if(pd != NULL)
   {
     // Derived 類型別, 可以使用指標pd訪問Derived類的成員
     cout << "& = " << pd << endl;
     pd->print();
   }
   else
   {
     Child* pc = dynamic_cast<Child*>(pb);
     
     if(pc != NULL)
     {
       // Child 類型別, 可以使用指標pc訪問Child類的成員
       cout << "& = " << pc << endl;
       cout << "I'm a Child. " << endl;
     }
     else
     {
       // Base 類型別, 可以使用指標pb訪問Base類的成員
       cout << "& = " << pc << endl; 
       cout << "I'm a Base. " << endl;
     }
   }
 }
 
 int main(int argc,char *argv[])
 {
   Base b;
   Derived d;
   Child c;
   
   test(&b);
   test(&d);
   test(&c);
   
   return 0;
 }
 /**
 * 執行結果:
 * & = 0
 * I'm a Base. 
 * & = 0x7ffccf0dd860
 * I'm a Derived.
 * & = 0x7ffccf0dd870
 * I'm a Child.
 */

(3)利用 typeid(推薦這種方法)

  1)typeid是一個關鍵字,專門用於動態型別識別;

  2)typeid 關鍵字返回對應引數的型別資訊,此型別資訊是一個type_info類物件;

    1.當引數為型別時,返回靜態型別資訊;

    2.當引數為變數時:1> 引數變數內部不存在虛擬函式表時,返回靜態型別資訊; 2> 引數變數內部存在虛擬函式表時,返回動態型別資訊;

    3.當引數為 NULL 時,將丟擲異常;

  3)typeid使用時需要包含標頭檔案<typeinfo>;

  4)typeid 使用時直接指定物件或者型別。

  5)typeid 在不同的編譯器內部實現是不同的;

int i = 0;

const type_info& tiv = typeid(i); // 將 i 的型別資訊放到 type_info 中去;
const type_info& tii = typeid(int);

cout << (tiv == tii) << endl; // 1

利用 typeid 實現型別識別

 #include <iostream>
  #include <string>
  #include <typeinfo>
  
  using namespace std;
  
  class Base
  {
  public:
   virtual ~Base()
   {
   }
 };
  
 class Derived : public Base
 {
 public:
   void print()
   {
     cout << "I'm a Derived." << endl;
   }
 };
  
 class Child : public Base 
 {
 public:
   void print()
   {
     cout << "I'm a Child." << endl;
   }
 };
  
 void test(Base* pb)
 {
   const type_info& tb = typeid(*pb);
   
   if( tb == typeid(Derived) )
   {
     Derived* pd = dynamic_cast<Derived*>(pb);
   
     cout << "& = " << pd << endl;
     pd->print();
   }
   else if( tb == typeid(Child) )
   {
     Child* pc = dynamic_cast<Child*>(pb);
     
     cout << "& = " << pc << endl;
     pc->print();
     
   }
   else if( tb == typeid(Base) )
   {
     cout << "& = " << pb << endl;
     cout << "I'm a Base. " << endl;
   }
   
   cout << tb.name() << endl;
 }
  
 int main(int argc,char *argv[])
 {
   Base b;
   Derived d;
   Child c;
   int index;
   char ch;
   
   const type_info& tp = typeid(b);
   const type_info& tc = typeid(d);
   const type_info& tn = typeid(c);
   const type_info& ti = typeid(index);
   const type_info& tch = typeid(ch);
   
   cout<<tp.name()<<endl;
   cout<<tc.name()<<endl;
   cout<<tn.name()<<endl;
   cout<<ti.name()<<endl;
   cout<<tch.name()<<endl;
   
   test(&b);
   test(&d);
   test(&c);
   
   return 0;
 }
 /**
  * 執行結果:
  * 4Base
  * 7Derived
  * 5Child
  * i
  * c
  * & = 0x7ffcbd4d6280
  * I'm a Base. 
  * 4Base
  * & = 0x7ffcbd4d6290
  * I'm a Derived.
  * 7Derived
 * & = 0x7ffcbd4d62a0
 * I'm a Child.
 * 5Child
 */ 

  結論:

  3 種動態型別的實現方法 建議選 第3種 (typeid)。

  對於多型實現,存在以下缺陷:

    1)必須從基類開始提供型別虛擬函式;

  2)所有的派生類都必須重寫型別虛擬函式;

  3)每個派生類的型別名必須唯一;

  對於 dynamic_cast 實現,只能得到型別轉換的結果,不能獲取真正的動態型別,同時dynamic_cast 必須多型實現。

到此這篇關於 詳解c++中的型別識別的文章就介紹到這了,更多相關c++ 型別識別內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!