关于C++中的类型转换

C++中定义了四种类型转换操作符:static_cast、const_cast、dynamic_cast和reinterpret_cast。

static_cast的用法类似于C语言中的强制类型转换,它可以将一种类型转换为另一种类型:

double n;
int a=static_cast<int>(n);

const_cast用于去除变量的常量属性,将一个const变量转变为非const变量:

const int a=0;
int b=const_cast<int>(a);

dynamic_cast则用于“将指向base class objects的pointers或references转型为指向derived class objects的pointers或references,并得知转型是否成功。”如果转型失败,会以一个null指针(当转型对象是指针)或一个exception(当转型对象是reference)表现出来。

Widget *pw;
update(dynamic_cast<SpecialWidget*>(pw));

void updateViaRef(SpecialWidget& rsw);
updateViaRef(dynamic_cast<SpecialWidget&>(*pw));

reinterpret_cast操作符的转换结果与编译平台息息相关,该操作符不具备移植性。它可以用来转换指针类型:

typedef void (*myFun)(int);
void fun1(int a)
{
	std::cout<<a<<std::endl;
}
int fun2(int a,int c)
{
	std::cout<<c<<std::endl;
	return a;
}
int main()
{
	void(*fun)(int);
	fun=reinterpret_cast<myFun>(fun2);
	fun(5);
	system("pause");
	return 0;
}

由于该操作符不具备移植性,某些情况下这样的转型可能会导致不正确的结果,因此不到万不得已,应该尽量避免函数指针转型。

原文地址:https://www.cnblogs.com/wickedpriest/p/5629294.html