紹介するといってもtypeid()という関数を使用するだけです。typeid()はtypeinfo.hで定義されているのでincludeする必要があります。
typeid()の引数には変数オブジェクトや型名(クラス名)を直接指定することが出来ます。
またtypeid()の戻り値同士を比較したりも出来ます。
サンプルコードを用意しました。
main.cpp
- #include <stdio.h>
- #include <typeinfo>
- #include "ConcreteClass.h"
- void main(void)
- {
- // ConcreteClassオブジェクト生成
- AbstractClass* obj = new ConcreteClass();
- // 型名取得
- const type_info& id = typeid(*obj);
- printf("%s\n", id.name());
- // method()の呼び出し
- obj->method();
- // 型を直接指定し型名を取得し比較
- if (typeid(ConcreteClass) == id) {
- printf("true\n");
- }
- delete obj;
- printf("hit any key...\n");
- while(getchar() == EOF) {}
- }
- </typeinfo></stdio.h>
AbstractClass.h
- #ifndef _ABSTRACT_CLASS_H_
- #define _ABSTRACT_CLASS_H_
- #include <stdio.h>
- #include <typeinfo.h>
- class AbstractClass
- {
- //----------------------------------
- // method
- //----------------------------------
- public:
- void method() {
- // 型情報の取得
- const type_info& id = typeid(*this);
- // 表示
- printf("AbstractClass-typeid:%s\n", id.name());
- // subMethod()の呼び出し
- this->subMethod();
- }
- protected:
- virtual void subMethod() = 0;
- };
- #endif
- </typeinfo.h></stdio.h>
ConcreteClass.h
- #ifndef _CONCRETE_CLASS_H_
- #define _CONCRETE_CLASS_H_
- #include <stdio.h>
- #include <typeinfo.h>
- #include "AbstractClass.h"
- class ConcreteClass : public AbstractClass
- {
- //----------------------------------
- // method
- //----------------------------------
- public:
- ConcreteClass() {
- // do nothing...
- }
- virtual ~ConcreteClass() {
- // do nothing...
- }
- protected:
- virtual void subMethod() {
- // 型情報の取得
- const type_info& id = typeid(*this);
- // 表示
- printf("ConcreteClass-type_id:%s\n", id.name());
- }
- };
- #endif
- </typeinfo.h></stdio.h>
0 件のコメント:
コメントを投稿