在介绍C++强制类型转换之前,我们先来看一看C语言风格的强制类型转换,的确,C风格的强制类型转换用起来很方便。
它的格式是:
(类型)变量
void test_c_cast()
{
//隐式类型转换(相近类型)
int i = 1;
double d = i;
//强转
int* p = &i;
int address = (int)p;
}
而C++有四种强制类型转换,分别是:
static_cast:转相关类型,相当于C语言的隐式类型转换
reinterpret_cast:相当于C语言的强转
const_cast:常量指针/引用转换为非常量指针/引用,并且仍然指向原来的对象
dynamic_cast:多态类型转换,将一个父类对象的指针/引用强转为子类指针/引用
接下来介绍用法:
一:static_cast 转相关类型,相当于C语言的隐式类型转换
void test_static_cast()
{
int i = 0;
double d = static_cast<double>(i);//返回一个临时对象
}
二:reinterpret_cast 相当于C语言的强转
typedef void(*Func)();//无参,无返回值
int Dosomething(int i)
{
cout << "Dosomething()" << endl;
return 0;
}
void test_reinterpret_cast()
{
//①
int* p = new int();
int address = reinterpret_cast<int>(p);
cout << address << endl;
//②
int ret = Dosomething(0);
Func f = reinterpret_cast<Func>(Dosomething);
f();//之前的Dosomething函数有参数有返回值,强转后无参也无返回值
}
三:const_cast 常量指针/引用转换为非常量指针/引用,并且仍然指向原来的对象
void test_const_cast()
{
const int num = 0;
//const int* p = #
int* p1 = const_cast<int*>(&num);
//此时num被去掉了常性
*p1 = 1;
cout << "num: " << num << " and *p1 = " << *p1 << endl;
}
四:dynamic_cast 多态类型转换,将一个父类对象的指针/引用强转为子类指针/引用
class Base{
public:
virtual void f1()
{
cout << "Base::f1()" << endl;
}
};
class Drive : public Base{
public:
virtual void f1()
{
cout << "Drive::f1()" << endl;
}
virtual void f2()
{
cout << "Drive::f2()" << endl;
}
};
void test_dynamic_cast()
{
//既然dynamic_cast是多态类型转换,所以必须有虚函数
//子类转父类直接转,切片;父类转子类,需要用dynamic_cast
//所以dynamic_cast会先检查能转不,不能转返回0。
Base b;
Drive d;
b = d;//子转父,切片
Base* pb = &b;
Drive* pd = dynamic_cast<Drive*>(pb);
}