bad_cast クラス

提供: RAD Studio
移動先: 案内検索

Typeinfo.h:インデックス への移動


ヘッダー ファイル

typeinfo.h

説明

dynamic_cast が、参照へのキャストに失敗した場合、式は bad_cast クラスを送出することができます。dynamic_cast がポインタ型へのキャストに失敗した場合、その結果は null ポインタです。

例:

実行時型識別を行う方法

#include <iostream>
#include <typeinfo.h>

using std::cout;

class __rtti Alpha {
   virtual void func() {};  // This makes Alpha a polymorphic class type.
};

class B : public Alpha {};

int main(void)
{
   B Binst;           // Instantiate class B
   B *Bptr;           // Declare a B-type pointer
   Bptr = &Binst;     // Initialize the pointer

   // THESE TESTS ARE DONE AT RUN TIME

   // Ask "WHAT IS THE TYPE FOR *Bptr?"

   if (typeid( *Bptr ) == typeid( B ) )
       cout << "Name is " << typeid( *Bptr).name();

   if (typeid( *Bptr ) != typeid( Alpha ) )
       cout << "\nPointer is not an Alpha-type.";

   return 0;
}

プログラムの出力:

Name is B
Pointer is not an Alpha-type.