C ++ in four types of conversion

C ++ in four types of conversion

static_cast, dynamic_cast, const_cast, reinterpret_cast is c ++ in four types of conversion

1、const_cast

const variable is used to non-const

2、static_cast

For a variety of implicit conversion, such as non-transfected const const, void * pointers turn

static_cast polymorphic transformation can be used up, turn down if successful but unsafe, the result is unknown;

For up conversion (or the pointer to the derived class reference into a base class shown) are safe ; and
for downlink conversion (pointer or reference to the base class to the derived class represented converted), because there is no dynamic type checking, it is unsafe to .

char/ a = 'a';
int b = static_cast<char>(a);//正确,将char型数据转换成int型数据

double *c = new double;
void *d = static_cast<void*>(c);//正确,将double指针转换成void指针

int e = 10;
const int f = static_cast<const int>(e);//正确,将int型数据转换成const int型数据

const int g = 20;
int *h = static_cast<int*>(&g);//编译错误,static_cast不能转换掉g的const属性

3、dynamic_cast

A dynamic type conversion. Class virtual function only for containing, for up and down conversion between the class hierarchy. You can only turn a pointer or reference. When down conversion, if the pointer is illegal to return NULL, a reference to throw exceptions. To learn more about the principles of internal conversion.

Up-conversion: conversion means is a subclass of the base class

Down conversion: conversion means is the base class to the sub-class

It is determined by the type of operating variables of time and is the same type to convert the time to execute the statement determines whether down conversion can be performed.

4、reinterpret_cast

Almost anything can be transferred, such as an int pointer turn, may be a problem, as little as possible;

5, why not use a cast of C?

C on the cast surface of what can turn looks powerful, but the conversion is not clear enough, can not be checked for errors, error-prone

Guess you like

Origin www.cnblogs.com/buerdepepeqi/p/12239377.html