dynamic_cast使用情况:
1)dynamic_cast一定要有虚函数;
2)向下类型转换;
3)有继承关系;
4)使用了RTTI技术,既运行时类型检查,运行时不成功,返回nullptr;
案例如下:
#include <iostream>
using namespace std;
class A
{
public:
virtual void show(void)
{
cout<<"AAAAAAAAAA"<<endl;
}
int num;
};
class B : public A
{
public:
void show(void)
{
cout<<"BBBBBBBBBBB"<<endl;
}
int age;
};
int main(void)
{
A a; //static_cast一般用于向上造型,本身是安全的
B* b = dynamic_cast<B*>(&a); //向下造型不安全;所以一般dynamic_cast进行类型检查
if(b != nullptr)
{
b->show();
}
return 0;
}
reinterpret_cast可以实现各种类型之间的转换,后果自负,代码如下:
#include <iostream>
using namespace std;
//reinterpret_cast 就是类似于C语言的强转
class Father
{
public:
};
class Son : public Father
{
public:
};
int main(void)
{
int n = 20; //整形转换指针
int* ptr = reinterpret_cast<int*>(n);
//指针类型转换
char* ptr2 = reinterpret_cast<char*>(ptr);
Son* son;
Father* father = nullptr;
// 父类转换子类
son = reinterpret_cast<Son*>(father); //不存在检查
return 0;
}