The Application of C ++ programming language can help developers greatly improve program development efficiency. Today we will introduce you to C ++ type conversion, which is one of the basic application skills. I hope you can fully master this knowledge to facilitate future reference.
- Discussion on the Application of C ++ Dynamic Array
- Examples of various C ++ inheritance Methods
- Analysis of the actual operation method of the C ++ Operator Overloading
- How to Implement C ++ Polymorphism
- C ++ static member initialization FAQs
The following discussion assumes that you have understood the C language programming and the Preliminary C ++ knowledge. Generally, there are two types of conversions: Explicit and Implicit ).
Implicit type conversion: it is believed that the implicit C ++ type conversion has been used and often used. For example, you can assign an integer variable to a floating point number, or, in a function that declares an integer parameter, floating point numbers are used as parameters. In these types, you may ignore them, but you are actually doing type conversion, which is only automatically completed by the system.
Explicit type conversion: in C, you can use (<data_type>) <Variable>, for example, using (int) ('C ') this method is used to convert a character variable or constant into an integer. This is called explicit type conversion.
Then there is the problem of Type compatibility. I believe this will be involved in all the C or C ++ tutorials. For example, you can convert a floating point number into an integer, however, you cannot convert an integer pointer to a floating point. In fact, the compatibility between conversions is a complicated concept. However, due to these complex types conversion mechanisms, C programming has gained more flexibility. However, from the perspective of C ++ OOP (Object-Oriented Programming), this is undoubtedly a very serious vulnerability, it can break through all the class packages created by C ++, or even constant restrictions.
In fact, the most acute problem is reflected in the forced conversion of pointer types.
I hope the readers will still remember the malloc function and void pointer in C. In C, you can smoothly put a void pointer (of course, this can even be any type of pointer) convert to any pointer, and then let point to and modify any memory segment. In C, in dynamic memory allocation processing <malloc. h> the above process is as follows.
However, C ++ realizes that C ++ is actually a major vulnerability, because programmers may inadvertently use these dangerous C ++ type conversions, using it to inadvertently access and modify some data units in the memory that you do not want to modify but are very important, resulting in a serious crash. Therefore, in C ++, several important measures have been taken to compensate for this vulnerability:
First, C ++ used the new and delete keywords to ban the original callback port and the error-prone malloc method, providing another solution for dynamic memory allocation to avoid type conversion;
Second, C ++ introduces the const mode, which makes it impossible (easily) to modify the variables and pointers defined as const. The compilation system intercepts them and provides error information;
The class encapsulation access permission also improves the situation.
However, our users may ask: "What should I do if I have to use these C ++ types to complete some special work ?"
The answer must be yes. This is the display conversion provided by iso c ++. It can break through class encapsulation or even constant restrictions.
In this case, the encapsulation of C ++ is not absolutely regular. It can be used as an exception, that is, the following keywords. However, he requires programmers who use it to clearly understand what he is doing, so four modes are provided for forced type conversion. This has another advantage, because when programmers encounter errors, such dangerous operations are definitely the first choice of suspects. By searching for such keywords, you can quickly locate your errors. The following are the conversion keywords for these four types of display:
Static_cast: used for benign conversions (General conversions, including automatic conversions). This keyword is not used during conversion;
Const_cast: used for conversion between const/volatile and non-const/volatile;
Reinterpret_cast: highly risky re-translation conversion, but it can achieve the most flexible C ++ type conversion;
Dynamic_cast: used for type-safe downward conversion.
The preceding three types of conversions are discussed in detail below:
The above display type conversion functions all require the template format. For example, note the following in the underline section:
- // Static_cast: benign and moderately benign conversion; security level: high
- Int num1 = 50; int a [20];
- Long num2 = static_cast <long> (num1 );
// Wide conversion with no information loss
- Char num3 = static_cast <char> (num3 );
// Narrow conversion with information loss. For specific conversion rules, refer to the relevant tutorial.
- Void * p = static_cast <void *> ();
// Use the forced conversion of void * to allow
- Float * q = static_cast <float *> (p );
// Use the forced conversion of void * to allow
- // Float * r = static_cast <float *> ();
// Error. The pointer type is not converted by void * and cannot be modified.
-- This is the usage of static_cast. It can only be used for value assignment Compatible C ++ type conversion. Otherwise, it cannot be used, and the security level is the highest. The compiler will block all type conversions that exceed the security level.
- // Const_cast: used to convert const/volatile to non-const/volatile. Security Level: Medium
- Const int a = 50; volatile int B = 100;
- Int * p = const_cast <int *> (& a); * p = 51;
- Cout <"a =" <a <endl; // correct output a should not change, a = 50
- Cout <"* p =" <* p <endl;
// But the magic is * p = 51. The memory has changed, but it will not be refreshed to const.
- Int * q = const_cast <int *> (& B); * q = 101;
- Cout <"B =" <B <endl;
// If volatile is used, refresh at any time. Therefore, the output value is B = 101, which has changed.
- Cout <"* q =" <* q <endl; // at this time, * q is naturally * q = 101
-- As you can see above, if you use const_cast for explicit forced type conversion, you can break through the constant limitation of C ++ and modify the memory pointed to by const, so there is a certain risk, however, if a programmer does this, he will basically realize this problem, so there is still some security.
- // Reinterpret_cast: the most dangerous, flexible, and omnipotent conversion method. The security level is low.
- Char str [] = "This is a string .";
- Float * r = reinterpret_cast <float *> (str );
// If reinterpret_cast is used, this will also be legal
-- Therefore, to safely use reinterpret_cast, you must convert the variable to its original type at the end. As you can imagine, it is dangerous to use a float pointer to operate a char array. Therefore, such a conversion method is no longer necessary, if you need to use it, first think about other methods.
However, in some cases, we still have to use this method. The flexibility of this method can even directly penetrate the encapsulation of an inherited class and directly access its protected member variables from the memory, it can even penetrate the private-level variables of the base class. You need to know that using the general method, this is impossible.
In fact, the C ++ type conversion shown above is just a habit. In fact, you can not declare such a type conversion statement, but the consequences may be serious, especially for experienced programmers. It can be imagined that when your program encounters a strange running error or even a crash, the biggest danger is likely to occur in these inexplicable type conversions, if you are not fully aware of this issue during coding, your program crash may infect you (and you crash together (~ _~)), However, if you are aware of this type of problem and use the explicit type conversion advocated above to identify your code, you may quickly find the error.
This kind of flexibility of C may be becoming the most criticized part of it. Flexibility is a double-edged sword. Maybe the advantages of this kind of usage can be seen from C to C ++.