引言
我们已经知道C语言里面有类型转换,分为显示和隐式转换。但为什么C++11又要更新类型转换呢?答案是:统一并改进C语言隐式类型转换的坑
下面来学习一下通俗的用法。
💡stactic_cast
用法:静态转换,对于静态类型进行转换,但是两个类型要相关(类似char,int,double),否则会报错,相当于C语言中的隐式转换。
double d = 12.21;
int i = 2;
int *pi;
i = (int)d;
i = static_cast<int>(d);
//pi = static_cast<int*>(i); // 不相关类型,会报错
💡const_cast
用法:最常用的用途就是删除变量的const属性,方便赋值
const int num = 10;
const int* ptr = #
int* ptr2 = const_cast<int*>(ptr);
// int* ptr2 = (int*)ptr; // C语言的操作
*ptr2 = 20; // 修改num的值
cout << num << endl;
cout << *ptr << endl;
cout << *ptr2 << endl;
💡reinterpret_cast
用法:用于将一种类型转换为另一种不同的类型,它是最危险的类型转换操作,需要格外谨慎使用。
int value = 42; int *ptr = &value; char *char_ptr = reinterpret_cast<char *>(ptr); //char *char_ptr = (char*)ptr; // C语言的写法
const_cast 和 reinterpre_cast 相当于C语言的强制类型转换
💡dynamic_cast
C++11中的dynamic_cast是一种安全的类型转换操作,适用于基类和派生类之间的类型转换,它可以在运行时进行类型检查,从而保证类型转换的安全。
用法:用于将一个父类对象的指针/引用转换为子类对象的指针或引用(动态转换)
向上转型:子类对象指针/引用->父类指针/引用(不需要转换,赋值兼容规则)
向下转型:父类对象指针/引用->子类指针/引用(用dynamic_cast转型是安全的)
class father
{
virtual void show()
{
cout << "father" << endl;
}
};
class son: public father
{
void show()
{
cout << "son" << endl;
}
};
void convert()
{
father f;
son s;
father* pf = &f;
son* ps = &s;
f = s; // 子类对象切割赋值给父类
s = f; // 不允许,报错,因为子类更大,父类更小
pf = ps; // 子类可以给父类,发生截断
ps = reinterpret_cast<son*>(pf);
ps = (son*)pf; // 父不能给子,得强转,但是不安全,会越界访问
ps = dynamic_cast<son*>pf; // 安全的,返回值为nullptr。
}
需要注意的是,
- dynamic_cast只能用于具有虚函数的类,因为它要求运行时类型信息必须存在。
- 此外,dynamic_cast只能用于指针或引用类型的转换,不支持将对象转换为另一种类型。如果类型转换不合法,dynamic_cast将返回nullptr。