Const_ cast,static_ cast, dynamic_ cast, reinterpret_ cast

Time:2021-3-4
  1. const_ Cast: used to convert const variables to non const variables
int n = 5;
int *k1 = const_ Cast (& n); // pointer
*k1 = 1;
int &k2 = const_ Cast (n); // reference
k2 = 2;
const int a = 10;
int* b = const_cast(&a);
*B = 11; // the attribute of pointer B becomes readable and writable

  2. Static cast: it has two functions, one is to replace implicit conversion, the other is to replace conversion between derived classes of base class

2.1) implicit conversion

int n = 10;
char c = 'a';
void *p = nullptr;
int *k = static_cast(p);
n = static_ Cast (c); // N becomes 97. The position of character a in the ascll code is equivalent to int n = (int) C;

2.2) conversion between derived classes of base class: it is safe to convert derived classes to base classes, but not vice versa, because derived classes expand many other methods. static_ Cast does not provide security checks.

  3. dynamic_ Cast: mainly used for conversion between derived classes of base class, providing security check, and usually base class should contain virtual function.

Note: it can be divided into two types: pointer type dynamic_ Cast and dynamic of reference type_ Cast type conversion. If the conversion fails, the pointer type will return 0 and the reference type will return bad_ cast。

  4. reinterpret_ Cast: almost everything can be turned, such as turning int to pointer, which may cause problems. Try to use it as little as possible.

 

reference resources:

  1. https://www.nowcoder.com/tutorial/93/a34ed23d58b84da3a707c70371f59c21    Niuke C + + interview dictionary Chapter 2 Section 1.

  2. https://www.cnblogs.com/-citywall123/p/13514067.html    There are four cast casts in C + +.