C ++ forced type conversion and forced type conversion

Source: Internet
Author: User

C ++ forced type conversion and forced type conversion

The forced Type conversion (Type Cast) of the C style is very simple. No matter what Type conversion is:

 

TYPE B = (TYPE)


The C ++ style type conversion provides four types of conversion operators for different applications.

 

  Const_castLiterally, it is to remove the const attribute.

  Static_castThe name can be understood as static type conversion. For example, convert int to char. (Basic type conversion)

  Dynamic_castThe name can be understood as dynamic type conversion. For example, the polymorphism type conversion between subclass and parent class.

  Reinterpret_cast, Only re-interpret the type, but no binary conversion is performed. (Pointer type conversion)

 

 

Const_cast

Remove the const or volatile attribute of the type.

Struct SA {int I ;}; const SA ra; // ra. I = 10; // directly modify the const type. The compilation error SA & rb = const_cast <SA &> (ra); rb. I = 10;


Static_cast

It is similar to the forced conversion of the C style. Unconditional conversion, static type conversion. Used:

1. Conversion between the base class and the subclass: it is safe to convert the subclass pointer to the parent class pointer, but it is not safe to convert the parent class pointer to the subclass pointer. (Dynamic_cast is recommended for dynamic type conversion between base class and subclass)

2. convert basic data types. Enum, struct, int, char, float, etc. Static_cast cannot be used to convert irrelevant types (such as non-base classes and sub-classes.

3. convert a null pointer to a null pointer of the target type.

4. convert any type of expression to void type.

5. static_cast cannot remove the const and volitale attributes of the type (use const_cast ).

Int n = 6; double d = static_cast <double> (n); // converts the basic type to int * pn = & n;Double * d = static_cast <double *> (& n) // irrelevant type pointer conversion, compilation error (reinterpret_cast is required, of course, the conversion result is incorrect)Void * p = static_cast <void *> (pn); // convert any type to void type

 

Dynamic_cast

Conditional conversion, dynamic type conversion, and runtime type security check (return NULL if conversion fails ):

1. Secure conversion between the base class and the subclass.

2. You must have a virtual function.

3. Cross conversion between different subclasses of the same base class. But the result is NULL.

 

Class BaseClass {public: int m_iNum; virtual void foo (){};// The base class must have virtual functions. Dynamic_cast can be used only when the polymorphism is maintained.}; Class DerivedClass: public BaseClass {public: char * m_szName [100]; void bar () {};}; BaseClass * pb = new DerivedClass (); derivedClass * pd1 = static_cast <DerivedClass *> (pb );// Subclass-> parent class, static type conversion, correct but not recommendedDerivedClass * pd2 = dynamic_cast <DerivedClass *> (pb );// Subclass-> parent class, dynamic type conversion, correctBaseClass * master = new BaseClass (); DerivedClass * pd21 = static_cast <DerivedClass *> (master );// Parent class-> subclass, static type conversion, dangerous! Access subclass m_szName member out of boundsDerivedClass * pd22 = dynamic_cast <DerivedClass *> (master );// Parent class-> subclass, dynamic type conversion, secure. The result is NULL.

  

Reinterpret_cast

The reinterpret_cast operator replaces most other C-style conversions. Reinterpret_cast converts a pointer to another pointer type, a number to a pointer, or a pointer to a number. Similar to C-style type conversion, when using the reinterpret_cast operator, you should know what you want to do. Sometimes, only the C-style type conversion works, but this does not mean that reinterpret_cast should never be used. The following example shows a simple memory allocation program that uses the void pointer to return a buffer with 100 characters. The Main () function assigns the returned result to a struct pointer. The conversion rules of C ++ are different from those of C ++.In the conversion rules of C ++, void * cannot be implicitly converted to char *. Therefore, type conversion is required.Reinterpret_cast instead of C type conversion is used below

 

#include <iostream> #include <cstring>//Create a buffer. // void* getmem() {static char buf[100];return buf; }int main() {char* cp = reinterpret_cast<char*>(getmem());strcpy(cp, "Hello, Woody"); std::cout << cp; return 0; }

 

 

 

  Reinterpret_castOnly re-interpret the type, but no binary conversion is performed:

1. The conversion type must be a pointer, reference, arithmetic type, function pointer, or member pointer.

2. bitwise conversion. It can convert a pointer to an integer, or an integer to a pointer (first, convert a pointer to an integer, and then convert the integer to the original type of pointer, you can also get the original pointer value ). However, you cannot convert a non-32bit instance to a pointer.

3. The most common purpose is to convert between function pointer types.

4. It is difficult to ensure portability.

Int doSomething () {return 0 ;}; typedef void (* FuncPtr) (); // FuncPtr is a pointer to a function. This function has no parameter, the return value type is void FuncPtr funcPtrArray [10]; // an array of 10 FuncPtrs pointers, which makes us assume that you want to (for some inexplicable reasons) store a pointer to the following function into the funcPtrArray array: funcPtrArray [0] = & doSomething; // compilation error! Type Mismatch. reinterpret_cast allows the compiler to view them in your way: funcPtrArray [0] = reinterpret_cast <FuncPtr> (& doSomething); // convert different function pointer types.
Usage
This operator is used in many ways. The operator modifies the operand type, but only re-explains the BIT model of the given object without binary conversion.
int *n= new int ;double *d=reinterpret_cast<double*> (n);
After calculation, d contains useless values. This is because reinterpret_cast only copies n bits to d without necessary analysis. Therefore, use reinterpret_cast. reinterpret_cast with caution to map to a completely different type. This keyword is used when we need to map the type back to the original type. The type we map to is only for xuanjicang and other purposes, which is the most dangerous of all mappings. (This is the original statement in C ++ programming philosophy) the difference between static_cast and reinterpret_cast lies mainly in multiple inheritance, such
class A {    public:    int m_a;}; class B {    public:    int m_b;}; class C : public A, public B {};
The following code:
C c;printf("%p, %p, %p", &c, reinterpret_cast<B*>(&c), static_cast <B*>(&c));
The first two outputs are the same, and the last offset is 4 bytes based on the original. This is because static_cast calculates the offset of parent-child pointer conversion, and convert it to the correct address (c contains m_a, m_ B, converted to B * pointer and then pointed to m_ B), but reinterpret_cast does not perform this conversion. Therefore, use reinterpret_cast with caution.

 

Use const_cast to remove the const attribute.

Use static_cast to convert basic types.

Daynamic_cast is used for type conversion between Polymorphism classes.

Reinterpreter_cast is used to convert pointer types of different types.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.