利用 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++ 类型识别内容请搜索易采站长站以前的文章或继续浏览下面的相关文章希望大家以后多多支持易采站长站!










