C++ 类型转换
C++风格的类型转换提供了4钟类型转换符来应对不同的场合的应用。
转换 | 说明 |
---|---|
static_cast | 一般的转换,静态类型转换,如int转换成char |
dynamic_cast | 通常在基类和派生类之间转换时使用,命名上理解是动态类型转换,如子类和父类之间的多台类型转换 |
const_cast | 主要针对const的转换,字面上理解就是去const属性。 |
reinterpret_cast | 用于进行没有任何关联之间的转换,比如一个字符指针转换为一个整数型,重新解释类型 |
4种类型转换的格式:
TYPE b = static_cast<TYPE>(a);
int a = 10;
char b = static_cast<char>(a);
class Person {};
class Teacher : public Person {};
//转换具有继承关系的对象指针 父类指针转成子类指针
Person *p1 = NULL;
Teacher* t1 = static_cast<Teacher*>(p1);
// 子类指针转换成父类指针
Teacher* t2 = NULL;
Person* p2 = static_cast<Person*>(t2);
Person p3;
Person& pref = p3;
Teacher& t3 = static_cast<Teacher&>(pref);
Teacher t4;
Teacher& t4Rfef = t4;
Person& p4 = static_cast<Person&>(t4Rfef);
// 子类指针转换为父类 安全
// 父类指针转为子类 不安全
Teacher *t =NULL;
Person* p = dynamic_cast<Person*>(t);
// 增加或去除const
const int* p = NULL;
int* p2 = const_cast<int*>(p);
int* p3 = NULL;
const int* p4 = const_cast<const int*>(p3);
// 强制类型转换
typedef void(*FUN1)(int,int)
typedef int(*FUN2)(int,char*);
// 函数指针转换
FUNC func1;
FUNC2 func2 = reinterpret_cast<FUNC2>(fun1);