C++におけるタイプ識別
3401 ワード
//Base* Base&
//Derived
Base* p = new Derived();
Base& r = *p;
タイプの違い:
void test(Base* b)
{
//
Derived* d = static_cast(b);
}
上記のコードでは、ベースクラスポインタが強制的にタイプをサブクラスポインタに変換できるかどうかは、ダイナミックタイプに依存します.
C++ではマルチステートを利用してダイナミックタイプを得る
例を挙げます.
#include
#include
using namespace std;
//
class Base
{
public:
//
virtual string type()
{
return "Base";
}
};
//
class Derived : public Base
{
public:
string type()
{
return "Derived";
}
void printf()
{
cout << "I'm a Derived." << endl;
}
};
//
class Child : public Base
{
public:
string type()
{
return "Child";
}
};
void test(Base* b)
{
/* */
// Derived* d = static_cast(b);
// ,
if( b->type() == "Derived" )
{
Derived* d = static_cast(b);
d->printf();
}
// cout << dynamic_cast(b) << endl;
}
int main(int argc, char *argv[])
{
Base b;
Derived d;
Child c;
test(&b);
test(&d);
test(&c);
return 0;
}
実行結果:
I'm a Derived.
上記のソリューションにはいくつかの欠陥があります.
では、これらの欠点を改善できる別の案はありますか?はい、ここでは新しい知識点を学びましょう.
typeid
キーワードの使用int i = 0;
const type_info& tiv = typeid(i);
const type_info& tii = typeid(int);
cout << (tiv == tii) << endl;
使用例:
#include
#include
#include
using namespace std;
//
class Base
{
public:
//
virtual ~Base()
{
}
};
class Derived : public Base
{
public:
void printf()
{
cout << "I'm a Derived." << endl;
}
};
void test(Base* b)
{
const type_info& tb = typeid(*b);
//tb type_info , name
cout << tb.name() << endl;
}
int main(int argc, char *argv[])
{
int i = 0;
// typeid
const type_info& tiv = typeid(i);
const type_info& tii = typeid(int);
cout << (tiv == tii) << endl;
Base b;
Derived d;
test(&b);
test(&d);
return 0;
}
出力結果:
1
4Base
7Derived