C++的类型转换
1.C语言的类型转换
隐式类型转换和显示类型转换
int main()
{
int i = 1;
//隐式类型转换
double d = i;
printf("%d, %.2f\n", i, d);
int *p = &i;
//显示的强制类型转换
int address = (int)p;
printf("%x,%d\n", p, address);
}
缺陷:转换的可视性比较差,所有的转换形式都是以一种相同形式书写,难以跟踪错误转换。
2.C++强制转换类型
2.1 static_cast
static_cast用于非多态类型转换(静态转换),编译器隐式执行的任何类型转换都可用static_cast,但它不能用于两个不相关的类型进行转换。
int main()
{
double d = 12.34;
int a = static_cast<int>(d);
cout << a << endl;
return 0;
}
2.2 reinterpret_cast
reinterpret_cast操作符通常为操作数的位模式提供较低层次的重新解释,用于将一种类型转换为另一种不同的类型,相当于C语言的显示类型转换。
ypedef void(*FUNC)();
int Dosomething(int i)
{
cout << "Dosomething" << endl;
return 0;
}
void Test()
{
// reinterpret_cast可以编译器以FUNC的定义方式去看待DoSomething函数
// 所以非常的BUG,下面转换函数指针的代码是不可移植的,所以不建议这样用
// C++不保证所有的函数指针都被一样的使用,所以这样用有时会产生不确定的结果
//
FUNC f = reinterpret_cast<FUNC>(Dosomething);
f();
}
int main()
{
double d = 12.34;
int a = static_cast<int>(d);
cout << a << endl;
int *pa = &a;
pa = reinterpret_cast<int*>(&d);
return 0;
}
2.3 const_cast
const_cast最常用的用途就是删除变量的const属性。
int main()
{
const int c = 10;
int* pc = const_cast<int*>(&c);
*pc = 1;
return 0;
}
2.4 dynamic_cast
dunamic_cast用于将一个父类对象的指针转换为子类对象的指针或引用。
向上转型:子类对象指针->父类指针/引用(赋值兼容规则)
向下转型:父类对象指针->子类指针/引用(dynamic_cast转型是安全的)
注意:(1)dynamic_cast只能用于含有虚函数的类
(2)dynamic_cast会先检查是否能转换成功,能成功则转换,不能则返回0
class Base
{
public:
virtual void func()
{
cout << "Base::func()" << endl;
}
private:
int _b;
};
class Derived :public Base
{
public:
void funcD()
{
cout << "Deriverd::funcD()" << endl;
}
private:
int _d;
};
void func(Base* pa)
{
pa->func();//实现多态
// 如果pa指向的是子类对象,可能需要借助子类的成员函数做一些其他事情
Derived* pb1 = dynamic_cast<Derived*>(pa);
Derived* pb2 = static_cast<Derived*>(pa);
cout << "pb1:" << pb1 << endl;
cout << "pb2:" << pb2 << endl;
if (pb1)
pb1->funcD();
if (pb2)
pb2->funcD();
}
int main()
{
Base b;
Derived d;
//赋值兼容规则
b = d;
Base*pb = &d;
Base& rb = d;
Derived* pd = dynamic_cast<Derived*>(&b);
func(&b);
func(&d);
return 0;
}
2.5 explicit
explicit关键字阻止经过转换构造函数进行隐式转换的发生(构造函数:单参构造函数或者除过第一个参数外其他参数都带用默认值)
class Date
{
public:
explicit Date(int year, int month = 1, int day = 1)
:_year(year)
, _month(1)
, _day(1)
{
cout << "Date::Data(int):" << this << endl;
}
Date& operator=(const Date& d)
{
if (this != &d)
{
_year = d._year;
_month = d._month;
_day = d._day;
}
return *this;
}
~Date()
{
cout << "Date::~Data(int):" << this << endl;
}
private:
int _year;
int _month;
int _day;
};
int main()
{
Date d1(2019);
//隐式转换,发生错误
d1 = 2020;
return 0;
}
2.6 为什么C++需要四种类型转换
(1)隐式类型转换有些情况可能会出现问题
(2)显示类型转换将所有的情况混合在一起,代码不够清晰
2.7在什么场景下进行类型转换
(1)在对对象(变量)进行初始化
(2)赋值
(3)传参
(4)返回值接受