C++强制类型转换之static_cast

  例1,将 double 类型转换为 int 类型

double d = 5.5;
int i = static_cast<int>(d);
printf("i = %d\n", i);

  运行结果如下:

i = 5

  例2,将 int 类型转换为 double 类型

int a = 10;
int b = 3;
double c = a / b;
double d = static_cast<double>(a) / static_cast<double>(b);
printf("c = %lf\n", c);
printf("d = %lf\n", d);

  运行结果如下:

c = 3.000000
d = 3.333333

  例3,将派生类指针转换为基类指针,由于这里是智能指针,所以 static_cast 变成了 static_pointer_cast。

// 基类
// 指向基类的智能指针
struct Sensor {};
typedef std::shared_ptr<Sensor> SensorPtr;
// 派生类
// 指向派生类的智能指针
struct CarVelocity : public Sensor {};
typedef std::shared_ptr<CarVelocity> CarVelocityPtr;
// 将派生类指针转换为基类指针
std::vector<SensorPtr> ret;
CarVelocityPtr can_measurement = std::make_shared<CarVelocity>();
ret.push_back(std::static_pointer_cast<Sensor>(can_measurement));

  例4,将基类指针转换为派生类指针

std::vector<SensorPtr> measurements;
std::vector<CarVelocityPtr> vec_can_meas;
auto can_meas = std::static_pointer_cast<CarVelocity>(measurements[i]);
vec_can_meas.push_back(can_meas);

  例5,将 type 类型的指针转换为空指针,将空指针转换为 type 类型的指针

type* pt_type = new type();
void* pt_void;
pt_void = static_cast<void*>(pt_type);

type* pt = static_cast<type*>(pt_void);

你可能感兴趣的:(C++,c++,开发语言)