|
目录
一、静态转换(static_cast)
- 用于类层次结构中基类(父类)和派生类(子类)之间指针或引用的转换。
- 进行上行转换(子转父)是安全的;
- 进行下行转换(父转子)是不安全的。
- 用于基本数据类型之间的转换,如把int转换成char,把char转换成int。
语法: static_cast<目标数据类型>(原变量/对象)
//内置数据类型
void test01()
{
char a = 'a';
double d = static_cast<double>(a);
cout << d << endl;
}
//对象转换
class Base{};
class Son :public Base{};
class Other{};
void test02()
{
Base * base = NULL;
//base 转为 Son * 父转子 向下类型转换 不安全
Son * son = static_cast<Son *>(base);
// son 转为 Base* 子转父 向上类型转换 安全
Base * base1 = static_cast<Base*>(son);
//base1 转 Other* 失败
//Other * other = static_cast<Other*>(base1);
}
二、动态转换(dynamic_cast)
- dynamic_cast主要用于类层次间的上行转换和下行转换,不允许内置数据类型转换;
- 在类层次间进行上行转换时,dynamic_cast和static_cast的效果是一样的;
- 在进行下行转换时,dynamic_cast具有类型检查的功能,比static_cast更安全;
- 发生多态,转换总是安全的
//2、动态类型转换
void test03()
{
//不允许内置数据类型转换
char a = 'a';
//double d = dynamic_cast<double>(a);
}
class Base1{ virtual void func1(){}; };
class Son1 :public Base1{ virtual void func1(){}; };
class Other1{};
void test04()
{
Base1 * base = NULL;
//base转为 Son1 * 父转子 不安全
//Son1 * son = dynamic_cast<Son1 *>(base); //失败 不安全
Son1 * son = NULL;
//son转 Base1 * 子转父 安全
Base1 * base1 = dynamic_cast<Base1*>(son);
//base1 转Other1*
//Other1 * other = dynamic_cast<Other1*>(base1); 不可以 失败
//如果发生多态,转换总是安全的
Base1 * base1 = new Son1;
Son1 * son1 = dynamic_cast<Son1*>(base1);
}
三、常量转换(const_cast)
该运算符用来修改类型的const属性。
- 常量指针被转化成非常量指针,并且仍然指向原来的对象;
- 常量引用被转换成非常量引用,并且仍然指向原来的对象;
不可以对非指针或非引用进行转换
//3、 const_cast常量转换
void test05()
{
//指针
const int * p = NULL;
//p 转为 int *
int * pp = const_cast<int *>(p);
const int * ppp = const_cast<const int *>(pp);
//引用
int num = 10;
int &numref = num;
const int & numRef2 = const_cast<const int &>(numref);
int & numRef3 = const_cast<int&>(numRef2);
//不可以对非指针或非引用进行转换
const int a = 10;
//int aa = const_cast<int>(a); 失败
}
四、重新解释转换(reinterpret_cast)
这是最不安全的一种转换机制,最有可能出问题。
主要用于将一种数据类型从一种类型转换为另一种类型。它可以将一个指针转换成一个整数,也可以将一个整数转换成一个指针.
基本不用