Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the conversion means of C++ and use it in conjunction with Explicit keywords

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "how to understand the conversion means of C++ and use it with Explicit keywords". In daily operation, I believe many people have doubts about how to understand the conversion means of C++ and use them in conjunction with Explicit keywords. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to understand the conversion means of C++ and use them in conjunction with Explicit keywords". Next, please follow the editor to study!

We do all kinds of forced conversions in C, and we often see this kind of conversion in C.

Memset (OTA_FLAG_ADDRESS, (uint8_t*) & OTA_Flag,sizeof (OTA_Flag))

The type conversion of C++ is very different from that of C, so how is the type conversion in C++ used? In addition to implicit conversion and display conversion in C++, display conversion is familiar to us. There are four display conversion functions: static_cast, dynamic_cast, const_cast and reinterpret_cast, which are mainly used in the forced conversion between inheritance classes.

Implicit transformation

The C++ language does not add two different types of values directly. It tries to unify the types of operands according to the type conversion rules before evaluating them. For example, int value = 3.14 + 3; this program can be compiled and passed, but the compiler may warn that the change operation loses precision. Such type conversions run automatically without programmer intervention, so they are called implicit conversions.

When implicit conversion occurs:

In the following cases, the compiler automatically converts the types of operands:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

In most expressions, an integer value smaller than the int type needs to be promoted to a larger integer type first, which will be implicitly converted

In conditions, non-Boolean values are converted to Boolean types

During initialization, the initial value is converted to the type of variable; in the assignment statement, the right Operand is converted to the type of the left Operand.

Type conversion also occurs when a function is called (argument type conversion)

Display conversion

C-style cast (Type Cast) is easy to understand, no matter what type of conversion can be used in the following ways

Type b = (Type) a

Of course, C++ also supports C-style casting, but C-style casting may bring some hidden dangers and make some problems difficult to detect. So C++ provides a set of casting functions that can be used in different situations.

C++ provides four functions to force type conversion, which are:

Static_cast, which is understood in naming as static type conversion. For most C conversions, you can use this function.

Const_cast literally means to go to the const attribute.

Dynamic_cast, which is understood in naming as dynamic type conversion. Such as polymorphic type conversions between subclasses and parents.

Reinterpret_cast, which only reinterprets the type, but does not convert the binary.

Static_cast:

Static_cast can be used for any type conversion that is clearly defined, as long as it does not include the underlying const, to give an example.

Double slop = static_cast (j) / iPlacement / forcibly converted to double int*pn = & n; double*dp = static_cast (& pn) / / unrelated type pointer conversion, compilation error void*p = & n; double*d = static_cast (& p) / / converts void* to the initial pointer type

Static_cast casts are checked only at compile time, but there is no run-time type checking to ensure the security of the conversion. At the same time, static_cast cannot remove the const, volitale, or _ _ unaligned attributes of expression.

Const_cast:

Const_cast can convert const pointer types to normal pointers, and const_cast operations cannot be converted between different types. Instead, it simply converts an expression it acts on into a constant. It can convert a data that is not a const type to a const type, or remove the const attribute. If an object itself is not a constant, it is legal to use forced type casting to gain write permission. However, if the object is a constant, then using const_cast to perform a write operation will have undefined consequences.

Only const_cast can change the constant property of an expression, and changing the constant property of an expression using other forms of naming forced type conversion will cause a compiler error. Similarly, you cannot change the type of expression with const_cast:

Const char * cp; char * Q = static_cast (cp); / / error: static_cast cannot convert the const property static_cast (cp); / / correct: string literals are converted to string type const_cast (cp); / / error: const_cast only changes constant attributes const_cast (cp); / / correct const int p = 0; int & rb = const_cast (p); / / correct rb = 10

Dynamic_cast:

1. The other three are done at compile time, dynamic_cast is handled at run time, and type checking is performed at run time.

two。 Cannot be used to cast built-in basic data types.

The 3.dynamic_cast transformation returns a pointer or reference to the class if successful, and NULL if the conversion fails.

4. If you use dynamic_cast for conversion, there must be a virtual function in the base class, otherwise the compilation will not pass. You can transfer the base class from the parent class, but it may be empty

5. When converting a class, dynamic_cast and static_cast have the same effect when converting upstream between class levels. When performing downstream conversions, dynamic_cast has the function of type checking, which is more secure than static_cast. The up conversion is the downward conversion to the subclass object, that is, the parent class pointer converts the subclass pointer. The success of the downward conversion also depends on the type to be converted, that is, the actual type of the object pointed to by the pointer to be converted must be the same as the object type after the conversion, otherwise the conversion fails.

Class BaseClass {public: int Num; virtualvoid foo () {}; / / the base class must have a virtual function. Keep multiple features to use dynamic_cast}; DerivedClass: public BaseClass {public: char*m_szName; void bar () {};}; int main (int argc,char** argv) {BaseClass* pb = new DerivedClass (); DerivedClass * pd1 = static_cast (pb); / / subclass-> parent class, static type conversion, correct but not recommended DerivedClass * pd2 = dynamic_cast (pb) / / subclass-> parent class, dynamic type conversion, correct BaseClass* pb2 = new BaseClass (); DerivedClass * pd21 = static_cast (pb2); / / parent class-> subclass, static type conversion, dangerous! Access subclass m_szName member out of bounds DerivedClass * pd22 = dynamic_cast (pb2); / / parent class-> subclass, dynamic type conversion, safe. The result is NULL.

Reinterpret_cast:

Reinterpret_cast is a mandatory type converter used to handle irrelevant type conversions, usually providing a lower-level reinterpretation of the bit pattern of operands! But it only reinterprets the bit model of the given object without binary conversion!

It is used for conversion between arbitrary pointers, between references, between pointers and sufficiently large int, and from integers to pointers. The most common use is to convert between function pointer types.

Please look at a simple code

Int doSomething () {return 0;}; typedef void (* FuncPtr) (); / / FuncPtr is a pointer to a function that has no arguments and returns a value of type void FuncPtr funcPtrArray [10]; / / an array of 10 FuncPtrs pointers lets us assume that you want (for some inexplicable reason) to store a pointer to the following function in the funcPtrArray array: funcPtrArray [0] = & doSomething;// compilation error! Type mismatches, reinterpret_cast can let the compiler look at them your way: funcPtrArray funcPtrArray [0] = reinterpret_cast (& doSomething); / / convert between different function pointer types

Explicit keyword (displayed type conversion operator)

C++ provides the keyword explicit to prevent implicit conversions through conversion constructors that should not be allowed. That is, constructors declared as explicit cannot be used in implicit conversions.

The explicit keyword can only be used on constructor declarations inside a class, not on function definitions outside the class. Now the Things class looks like this:

Class Things {public: Things (const std::string&name = ""); explicit operator int () const {return val;} / / the compiler does not automatically execute this type of}

Let's take a look at a better example for comparison:

/ / implicit conversion of classes through constructors: # include using namespace std; class A {}; class B {public: / / conversion from A (constructor): B (const A & x) {} / / conversion from A (assignment): B & operator= (const A & x) {return * this;} / / conversion to A (type-cast operator) operator A () {return A ();}}; int main () {A foo; B bar = foo / / call the constructor to achieve implicit type conversion bar = foo; / / calls assignment foo = bar; / / calls type-cast operator, equivalent to foo = A (bar); return 0;}

Consider another example of using explicit:

# include using namespace std; class A {}; class B {public: explicit B (const A & x) {} B & operator= (const A & x) {return * this;} operator A () {return A ();}}; void fn (B x) {} / / when we want x to be only type B, we need to prohibit implicit type conversion int main () {A foo; B bar (foo) / / explicit type conversion is required, B bar = foo; bar = foo; foo = bar; / / fn (foo) is no longer allowed; / implicit type conversion fn (bar) is not allowed; return 0;} this is the end of the study on "how to understand the conversion means of C++ and use it with the Explicit keyword". Hope to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report