本文主要转载自一条傻傻的二哈
https://blog.csdn.net/qq_40421919/article/details/90677220
const_cast
用于将const变量转为非const
他的功能就是删除变量的const属性,方便再次赋值
该转换在编译时完成,用于解除const,volatile修饰符,只能转换指针或者引用
#include<iostream>
using namespace std;
class A {
public:
int data;
};
int main()
{
const A a = { 200 };
//A a1 = const_cast<A>(a); //错误,const_cast 目标类型只能是引用或者指针
//a1.data = 100;
A& a2 = const_cast<A&>(a);
a2.data = 100;
cout << a.data << ' ' << a2.data << endl;
A* a3 = const_cast<A*>(&a);
a3->data = 50;
cout << a.data << ' ' << a3->data << endl;
const int x = 3;
int& x1 = const_cast<int&>(x);
x1 = 200;
cout << x << ' ' << x1 << endl;
int* x2 = const_cast<int*>(&x);
*x2 = 300;
cout << x << ' ' << *x2 << endl;
return 0;
}
static_cast 静态类型转化
在编译期内即可决定其类型的转换
用的最多,对于各种隐式转换,非const转const,void*转指针等, static_cast能用于多态向上转化,如果向下转能成功但是不安全,结果未知;
#include <iostream>
using namespace std;
int main(void)
{
double dPi = 3.1415926;
int num1 = (int)dPi; //c语言的旧式类型转换
int num2 = dPi; //隐式类型转换
// 静态的类型转换:
// 在编译的时进行基本类型的转换 能替代c风格的类型转换 可以进行一部分检查
int num3 = static_cast<int> (dPi); //c++的新式的类型转换运算符
cout << "num1:" << num1 << " num2:" << num2 << " num3:" << num3 << endl;
return 0;
}
dynamic_cast 子类和父类之间的多态类型转换
用于动态类型转换。只能用于含有虚函数的类,用于类层次间的向上和向下转化。只能转指针或引用。向下转化时,如果是非法的对于指针返回NULL,对于引用抛异常。
dynamic_cast实现方式
编译器会在每个含有虚函数的类的虚函数表的前四个字节存放一个指向_RTTICompleteObjectLocator结构的指针,当然还要额外空间存放_RTTICompleteObjectLocator及其相关结构的数据。里面存放了vptr相对this指针的偏移,构造函数偏移(针对虚拟继承),type_info指针,以及类层次结构中其它类的相关信息。如果是多重继承,这些信息更加复杂。
reinterpret_cast
数据的二进制重新解释,但是不改变其值
几乎什么都可以转,比如将int转指针,可能会出问题,尽量少用;
einterpret的含义是重新解释,可将一种类型转换成另一种不相关类型,对应C中的强制类型转换,处理无法进行隐式转换的情况。
#include<iostream>
using namespace std;
class Dog{
public:
void run()
{
cout << "dog run" << endl;
}
};
class Cat{
public:
void mew()
{
cout << "cat mew " << endl;
}
};
int main()
{
Dog* a = new Dog();
a->run();
Cat* b = reinterpret_cast<Cat*>(a); //强制类型的转换
b->mew();
return 0;
}
参考链接:
https://blog.csdn.net/qq_40421919/article/details/90677220