C/C++ 四种类型转换

发布时间 2023-06-09 10:50:57作者: 心碎战士

1. 去常转换 const_cast

把常量指针或引用转换为非常量指针或引用,或者反之,并仍然指向原来的对象。强制转换类型必须是指针或引用。

const int a = 10;
const int &b = 20;
int& ra = const_cast<int&> (a); // 把常量引用转换为非常量引用
int* p = const_cast<int*> (&b); // 把常量指针转换为非常量指针
int c = const_cast<int>(a); // 错误,转换类型必须是指针或引用
int d = const<int>(b);// 错误,转换类型必须是指针或引用

 

2. 静态转换 static_cast

只能在内置的数据类型之间相互转换,对于类只能在有联系的指针类型间进行转换。

用于基本类型间的转换,不能用于基本类型指针间的转换。

对于有继承关系类对象之间的转换,派生类指针或引用转换成基类(上行转换)时安全,基类指针或引用转换成派生类(下行转换)时不安全。

int a = 10;
int b = 20;
float ft = 12.25f;
b = static_cast<float>(ft);
int* ip = static_cast<int*>(&ft); // 错误,不能用于基本类型指针间的转换

class Base
{
};
class Derived : public Base
{
};

Derived derived;
Base base;
derived = static_cast<Derived>(base); //

对void*的转换,不安全。

int a = 10;
void* vi = &10;
float* fp = static_cast<float*>(vi);// 不安全,当读取*fp的值时会扩大读取的字节个数,造成读取数据错误的情况