What is the difference between the four transformations of const_cast,dynamic_cast,reinterpret_cast,static_ castings
The content of this article mainly focuses on what is the difference between the four transformations of const_cast,dynamic_cast,reinterpret_cast,static_ cast. the content of the article is clear and well-organized, which is very suitable for beginners to learn and is worth reading. Interested friends can follow the editor to read together. I hope you can get something through this article!
C++ is a strongly typed language, and the type checking is very strict. We can use the (NewType) Expression in C language to override the return value of a variable or expression, or we can use the new conversion operator provided in C++: const_cast,dynamic_cast,reinterpret_cast,static_cast. Here are four different scenarios used by transformations.
One, const_cast
As the name implies, const_cast is used to remove the constancy of an object so that Chang Liang can be modified. The type in const_cast (varible) must be a pointer, reference, or pointer to a member of the object type. For example, the following usage is wrong:
Change int to int& to compile normally, and the output a value is 4:
Three classes are defined. There are different member functions TestB () and TestC () in parent class A, subclass B and C, respectively, and then use A pointer to point to the A _ Magi B ~ C object from new and put it into an array:
At this point, the values of str and p are exactly the same, and the purpose of reinterpret_cast is to interpret the value of the pointer str as an integer in a binary way.
This kind of operation, which I have never used in practical projects, is limited to the understanding of written basic knowledge.
Four, static_cast
Static_cast is used to deal with implicit conversion, which is equivalent to (NewType) Expression overturn in C language. it can turn int into float, char* into int, the pointer to the base class into a pointer to a subclass, and non-const into a const object, but it cannot convert a const object into non-const (this is the function of const_cast).
Thank you for your reading. I believe you have a certain understanding of the question of "what is the difference between the four conversions of const_cast,dynamic_cast,reinterpret_cast,static_ castings?" go ahead and practice it. If you want to know more about it, you can follow the website! The editor will continue to bring you better articles!