Home  >  Article  >  Backend Development  >  Four types of casts in C++_Basic usage and usage scenarios

Four types of casts in C++_Basic usage and usage scenarios

php是最好的语言
php是最好的语言Original
2018-08-01 14:20:393641browse

Type conversion in C:

Let’s start from the beginning, which is the C language. We are used to using C-like type conversion because it is powerful And simple.

mainly has two forms:

  • (new-type) expression

  • new-type ( expression)

The C-style conversion format is very simple, but it has many shortcomings:

 1. The conversion is too arbitrary and can be converted between any types. You can convert a pointer to a const object to a pointer to a non-const object, and convert a pointer to a base class object to a pointer to a derived class object. The gap between these conversions is very huge, but traditional C Language-style casts make no distinction between these.

 2.C-style conversion does not have unified keywords and identifiers. For large systems, it is easy to miss and ignore when doing code troubleshooting.

Type conversion in C:

C style perfectly solves the above two problems. 1. Type conversion is subdivided and four different types of conversion are provided to support conversions with different needs; 2. Type conversion has a unified identifier, which is convenient for code troubleshooting and inspection. The four conversions are introduced below: static_cast, dynamic_cast, const_cast and reinterpreter_cast.

  • static_cast, the naming is understood to be static type conversion. Such as converting int to char.

  • dynamic_cast, the naming is understood to be dynamic type conversion. Such as polymorphic type conversion between subclass and parent class.

  • const_cast, literally means to remove const attributes.

  • reinterpreter_cast, only reinterprets the type, but does not perform binary conversion.

1. static_cast conversion

 1.Basic usage: static_cast expression

 2.Usage scenarios:

a. Used for conversion of pointers or references between base classes and derived classes in the class hierarchy

Upstream conversion (derived class-->base Class) is safe;

Downcast (base class --> derived class) is unsafe because there is no dynamic type checking.

b. Used for conversion between basic data types, such as converting int to char. This brings security issues and must be ensured by the programmer

c. Convert the null pointer to Null pointer of target type

d. Convert any type of expression to void type

3.Usage features

a. Mainly execute non- Polymorphic conversion operations are used to replace the usual conversion operations in C

b. It is recommended to use static_cast to indicate and replace implicit conversions

int n = 6;double d = static_cast<double>(n); // 基本类型转换int *pn = &n;double *d = static_cast<double *>(&n) //无关类型指针转换,编译错误void *p = static_cast<void *>(pn); //任意类型转换成void类型

2. dynamic_cast conversion

1.Basic usage: dynamic_cast expression

2.Usage scenarios: Use dynamic_cast only when converting between derived classes, type -id must be a class pointer, class reference or void*.

 3.Usage Features:

a. The base class must have a virtual function, because dynamic_cast is a runtime type check and requires runtime type information, and this information It is stored in the virtual function table of the class. Only a class that defines a virtual function will have a virtual function table (if a class does not have a virtual function, in a general sense, the designer of this class does not want it to become a base class) .

b. For downward conversion, dynamic_cast is safe (when the types are inconsistent, the converted pointer is a null pointer), while static_cast is unsafe (when the types are inconsistent, the converted pointer is a pointer with the wrong meaning) , may cause various problems such as memory trampling and illegal access)

c. dynamic_cast can also perform cross conversion

class BaseClass 
{public:
  int m_iNum;
  virtual void foo(){};//基类必须有虚函数。保持多台特性才能使用dynamic_cast};class DerivedClass: public BaseClass 
{public:
  char *m_szName[100];
  void bar(){};
};
  
BaseClass* pb = new DerivedClass();
DerivedClass *pd1 = static_cast<DerivedClass *>(pb);//子类->父类,静态类型转换,正确但不推荐DerivedClass *pd2 = dynamic_cast<DerivedClass *>(pb);//子类->父类,动态类型转换,正确BaseClass* pb2 = new BaseClass();//父类->子类,静态类型转换,危险!访问子类m_szName成员越界DerivedClass *pd21 = static_cast<DerivedClass *>(pb2);//父类->子类,动态类型转换,安全的。结果是NULLDerivedClass *pd22 = dynamic_cast<DerivedClass *>(pb2);

3. const_cast conversion

1.Basic usage: const_castexpression

2.Usage scenarios:

a. Convert a constant pointer to a non-const pointer and still point to the original Object

 b. The constant reference is converted into a non-const reference and still points to the original object

 3.Usage features:

 a. cosnt_cast It is the only conversion operator among the four type conversion operators that can operate on constants

b. Removing constantness is a dangerous action, so try to avoid using it. A specific scenario is: when a class provides overloading through const, the non-const function usually calls const_cast to convert the parameters into constants, then calls the constant function, and then gets the result and then calls const_cast to remove the constness.

struct SA 
{
  int i;
};const SA ra;//ra.i = 10; //直接修改const类型,编译错误SA &rb = const_cast<SA&>(ra);
rb.i = 10;

4. reinterpret_cast conversion

1.Basic usage: reinterpret_castexpression

2.Usage scenarios: Don’t use this conversion character as a last resort, high-risk operation

3.Usage features:  

a. reinterpret_cast reinterprets the data from the bottom layer, relying on Specific platforms have poor portability

b. Reinterpret_cast can convert integers into pointers and pointers into arrays

c. Reinterpret_cast can perform unscrupulous conversions in pointers and references

int doSomething(){return 0;};//FuncPtr is 一个指向函数的指针,该函数没有参数,返回值类型为 voidtypedef void(*FuncPtr)();//10个FuncPtrs指针的数组 让我们假设你希望(因为某些莫名其妙的原因)把一个指向下面函数的指针存//入funcPtrArray数组:FuncPtr funcPtrArray[10];

funcPtrArray[0] = &doSomething;// 编译错误!类型不匹配,reinterpret_cast可以让编译器以你的方法去看待它们:funcPtrArrayfuncPtrArray[0] = reinterpret_cast<FuncPtr>(&doSomething);//不同函数指针类型之间进行转换

总结:

去const属性用const_cast。

基本类型转换用static_cast。

多态类之间的类型转换用daynamic_cast。

不同类型的指针类型转换用reinterpreter_cast。

相关文章:

C++ 的强制类型转换

【c#教程】C# 类型转换

相关视频:

PHP数据类型转换之自动类型转换

The above is the detailed content of Four types of casts in C++_Basic usage and usage scenarios. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn