一、dynamic_cast
主要作用是将父类指针(引用)转换为子类指针(引用)
int main()
{
//一、dynamic_cast:
human *phuman = new man;
human &p = *phuman;
phuman->eat();//eat()为虚函数,则可以调用
//phuman->sleap(); 基类指针不能直接调用子类的非虚成员函数
((man*)phuman)->sleep();//C语言转换方法,将基类指针转换为子类指针,可以调用,但不建议
man *pman = dynamic_cast<man*>(phuman);//C++转换方法,将父类指针转换为子类指针
if (pman != nullptr)
{
cout << "指针转换成功" << endl;
}
else
{
cout << "指针转换失败" << endl;
}
try
{
man &manbm = dynamic_cast<man&>(p); //将父类的引用转换成子类引用
//转换成功直接进入下一步,发生错误进入catch
cout << "引用转换成功" << endl;
}
catch (std::bad_cast)
{
cout << "引用转换失败" << endl;
}
delete phuman;
return 0;
}
二、typeid运算符
用法:typeid(指针或引用或表达式) 拿到对象类型信息,typeid会的返回一个常量对象的引用,是一个标准库类型,type_info类类型
1、指针或引用类型
human *phuman = new human;
human &q = *phuman;
cout << typeid(*phuman).name() << endl;
cout << typeid(q).name() <<endl;
delete phuman;
?2、表达式
int a = 0;
char b[5];
cout << typeid(a).name() << endl;
cout << typeid(b).name() << endl;
cout << typeid(12.2).name() << endl;
cout << typeid("abc").name() << endl;
?
3、判断指针的定义是否相同
这里注意:基类中必须要有虚函数,基类指针才能动态绑定到子类对象,才能进行判断,因为typeid返回的是静态类型(定义时的类型)。
human *phuman1 = new man;
human *phuman2 = new women;
cout << "------------------------------------" << endl;
if (typeid(phuman1) == typeid(phuman2))
{
cout << "两个指针的定义相同" << endl;
}
if (typeid(*phuman1) == typeid(man))//基类中有虚函数才可以
{
cout << "phuaman指向man" << endl;
}
if (typeid(*phuman1) == typeid(*phuman2))
{
cout << "两个指针的指向相同" << endl;
}
else
{
cout << "两个指针的指向不相同" << endl;
}
cout << "------------------------------------" << endl;
delete phuman1;
delete phuman2;
?
?
4、type_info
? ? typeid拿到对象类型信息,typeid会的返回一个常量对象的引用,是一个标准库类型,type_info类类型
?(1).name()方法,返回的是一个字符串,类名
human *phuman1 = new man;
human *phuman2 = new women;
cout << "------------------------------------" << endl;
const type_info &p1 = typeid(*phuman1);
const type_info &p2 = typeid(*phuman2);
cout << p1.name() << endl;
cout << p2.name() << endl;
if (p1 == p2)
{
cout << "p2和p1类型相同" << endl;
}
else
{
cout << "p2和p1类型不同" << endl;
}
cout << "------------------------------------" << endl;
delete phuman1;
delete phuman2;
?
?
5、RTTI与虚函数表
高深的知识,学习对象模型时续再研究
?
?
|