代码改变世界

函数类型转换

2018-10-21 14:07  mengjuanjuan1994  阅读(207)  评论(0编辑  收藏  举报

1. static_cast   

用于内置的数据类型(int, char)

eg1:

int a = 97;

char c = static_cast<char>(a);

 用于具有继承关系的指针或者引用  

eg2:

class Animal

{

};

class Cat: public Animal

{

};

Animal *ani1 = NULL;

Cat *cat1 = static_cast<Cat*>(ani1);

Animal *ani2 = static_cast<Animal *>(cat1);

2. dynamic_cast

不能转换内置的数据类型,只能转换具有继承关系的指针或引用,在转换前会进行对象类型检查(即只能从子类指针转换成父类指针,从范围大的转成范围小的)

eg:

class Animal

{

};

class Cat: public Animal

{

};

Cat *cat1 = NULL;

Animal *ani2 = static_cast<Animal *>(cat1);

3. const_cast

用于内置的数据类型(int, char)的指针或引用,增加或去除变量的const性

eg1:

int a = 0;

int &c = a;

const int& b = const_cast<const int&>(c);

用于具有继承关系的指针或引用,增加或去除变量的const性

eg2:

const int* p1 = NULL;

int* p2 = const_cast<int*>(p1);

int* p3 = NULL;

const int* p4 = const_cast<const int*>(p3);

4. reinterpret_cast

强制类型转换,可以转换无关的类型。