static_cast
功能:完成编译器认可的隐式类型转换。
格式type1 a;
type2 b = staic_cast(a);将type1的类型转化为type2的类型;
使用范围:
(1)基本数据类型之间的转换,如int->double;
int a = 6;
double b = static_cast(a);
(2)派生体系中向上转型:将派生类指针或引用转化为基类指针或引用(向上转型);
class base{ …. }
class derived : public base{ …. }
base *b;
derived *d = new derived();
b = static_cast<base *>(d);
dynamic_cast
功能:执行派生类指针或引用与基类指针或引用之间的转换。
格式:
(1) 其他三种都是编译时完成的,dynamic_cast是运行时处理的,运行时要进行运行时类型检查;
(2) 基类中要有虚函数,因为运行时类型检查的类型信息在虚函数表中,有虚函数才会有虚函数表;
(3) 可以实现向上转型和向下转型,前提是必须使用public或protected继承;
例子:
向上转型:
class base{ … };
class derived : public base{ … };
int main()
{
base *pb;
derived *pd = new derived();
pb = dynamic_cast<base *>(pd);
return 0;
}
向下转型:
class base{ virtualvoid func(){} };
class derived : public base{ void func(){} };
int main()
{
base *pb = new base();
derived *pd = dynamic_cast<derived *>(pb);//向下转型
return 0;
}
const_cast
只能对指针或者引用去除或者添加const属性,对于变量直接类型不能使用const_cast;不能用于不同类型之间的转换,只能改变同种类型的const属性。
如:
const int a= 0;
int b = const_cast(a);//不对的
const int *pi = &a;
int * pii = const_cast<int *>pi;//去除指针中的常量性,也可以添加指针的常量性;
const_cast的用法:
(1)常用于函数的形参是一个非const的引用,我想要穿进去一个const的引用,可以使用const_cast<Type&>para;去除实参的常量性,以便函数能够接受这个参数。
(2)一个const对象,我们想要调用该对象中的非const函数,可以使用const_cast去除对象的常量性;
reinterpret_cast
- 用于进行各种不同类型的指针之间、不同类型的引用之间以及指针和能容纳指针的整数类型之间的转换,reinterpret_cast 转换时,执行的过程是逐个比特复制的操作。
#include <iostream>
using namespace std;
class A
{
public:
int i;
int j;
A(int n) :i(n), j(n) { }
};
int main()
{
A a(100);
int &r = reinterpret_cast<int&>(a); // 强行让 r 引用 a
r = 200; // 把 a.i 变成了 200
cout << a.i << "," << a.j << endl; // 输出 200,100
int n = 300;
A *pa = reinterpret_cast<A*> (&n); // 强行让 pa 指向 n
pa->i = 400; // n 变成 400
pa->j = 500; // 此条语句不安全,很可能导致程序崩溃
cout << n << endl; // 输出 400
long long la = 0x12345678abcdLL;
pa = reinterpret_cast<A*>(la); // la太长,只取低32位0x5678abcd拷贝给pa
unsigned int u = reinterpret_cast<unsigned int>(pa); // pa逐个比特拷贝到u
cout << hex << u << endl; // 输出 5678abcd
typedef void(*PF1) (int);
typedef int(*PF2) (int, char *);
PF1 pf1 = nullptr;
PF2 pf2;
pf2 = reinterpret_cast<PF2>(pf1); // 两个不同类型的函数指针之间可以互相转换
}
本文介绍了C++中的四种类型转换方法:static_cast用于编译时隐式类型转换,dynamic_cast处理派生类指针的运行时类型检查,const_cast改变const属性,reinterpret_cast用于不同类型的指针和整数间的转换。着重讲解了它们的用途、规则和示例。
868

被折叠的 条评论
为什么被折叠?



