动态类型指基类指针所指向的对象的实际类型
child*c=(child*)p //若p动态类型为parent,可能出现无法预知错误
基类指针是否可以强制类型转换为子类指针取决于动态类型
——/根据多态
使用多态进行动态类型识别缺陷(维护性很差):
①须从基类提供类型虚函数②所有派生类须重写类型虚函数③每个派生类类型ID须唯一
如缺virtual ~Parent(){},报source type is not polymorphic错,因:
dynamic_cast主用于基类派生类间转换,要求目标对象类型为多态
用于指针转换,转换失败返回空;用于引用转换,转换失败引发bad_cast异常
——/动态获得任意变量类型信息
dynamic_cast缺陷:只能用于具有虚函数的类族(工程上常把析构函数定义为虚函数)
typeid关键字用于动态获取类型信息,返回一type_info类对象
typeid参数为NULL,抛出bad_typeid异常,包含<typeinfo>
若无virtual ~Parent(){},结果Parent Parent
——/
可通过多态或dynamic_cast关键字或typeid关键字进行动态类型识别
child*c=(child*)p //若p动态类型为parent,可能出现无法预知错误
基类指针是否可以强制类型转换为子类指针取决于动态类型
——/根据多态
class Parent
{
public:
enum { ID = 0 };
virtual int type()
{
return ID;
}
};
class Child : public Parent
{
public:
enum { ID = 1 };
int type()
{
return ID;
}
};
void test(Parent* p)
{
if( p->type() == Child::ID )
{
Child* c = (Child*)p;
cout<<"Dynamic Type: "<<"Child"<<endl;
}
if( p->type() == Parent::ID )
{
cout<<"Dynamic Type: "<<"Parent"<<endl;
}
}
int main()
{
Parent parent;
Child child;
test(&parent);
test(&child);
return 0;
}
——/
使用多态进行动态类型识别缺陷(维护性很差):
①须从基类提供类型虚函数②所有派生类须重写类型虚函数③每个派生类类型ID须唯一
class Parent
{
public:
virtual ~Parent(){} //工程中常如此
};
class Child : public Parent
{
};
class NewChild : public Parent
{
};
void test(Parent* p)
{
Child* c = dynamic_cast<Child*>(p);
if( c != NULL )
{
cout<<"Child"<<endl;
}
else
{
if( dynamic_cast<NewChild*>(p) != NULL )
{
cout<<"NewChild"<<endl;
}
else
{
cout<<"Parent"<<endl;
}
}
}
int main()
{
Parent parent;
Child child;
NewChild nc;
test(&parent);
test(&child);
test(&nc);
return 0;
}
结果:Parent Child NewChild
如缺virtual ~Parent(){},报source type is not polymorphic错,因:
dynamic_cast主用于基类派生类间转换,要求目标对象类型为多态
用于指针转换,转换失败返回空;用于引用转换,转换失败引发bad_cast异常
——/动态获得任意变量类型信息
dynamic_cast缺陷:只能用于具有虚函数的类族(工程上常把析构函数定义为虚函数)
typeid关键字用于动态获取类型信息,返回一type_info类对象
typeid参数为NULL,抛出bad_typeid异常,包含<typeinfo>
class Parent
{
public:
virtual ~Parent(){}
};
class Child : public Parent{};
void test(Parent* p)
{
if( typeid(*p) == typeid(Child) )
{
cout<<"Child"<<endl;
}
else if( typeid(*p) == typeid(Parent) )
{
cout<<"Parent"<<endl;
}
}
int main()
{
Parent parent;
Child child;
int index;
char ch;
const type_info& tp = typeid(parent);
const type_info& tc = typeid(child);
const type_info& ti = typeid(index);
const type_info& tch = typeid(ch);
cout<<tp.name()<<endl;
cout<<tc.name()<<endl;
cout<<ti.name()<<endl;
cout<<tch.name()<<endl;
test(&parent);
test(&child);
return 0;
}
结果:6Parent 5Child I c Parent Child
若无virtual ~Parent(){},结果Parent Parent
——/
可通过多态或dynamic_cast关键字或typeid关键字进行动态类型识别