C ++ type conversion

Source: Internet
Author: User
The type conversion method used in C language is generally forced type conversion. Syntax: (type specifier) (expression), for example: (float) a converts a to a real type, (int) (x + y) converts the result of x + y to an integer. In C language, the type conversion mode may make people feel inaccurate and not strict, because no matter what the expression value is, the system automatically converts it to the type of the left variable of the value assignment operator. C language type conversion

The type conversion method used in C language is generally forced type conversion. Syntax: (type specifier) (expression), for example: (float) a converts a to a real type, (int) (x + y) converts the result of x + y to an integer.
In C language, the type conversion mode may make people feel inaccurate and not strict, because no matter what the expression value is, the system automatically converts it to the type of the left variable of the value assignment operator.

C ++ type conversion

Const_cast, literally, is to remove the const attribute.
Static_cast, which is named static type conversion. For example, convert int to char.
Dynamic_cast, which is named as dynamic type conversion. For example, the polymorphism type conversion between subclass and parent class.
Reinterpret_cast, only re-interpreting the type, but no binary conversion is performed.

Const_cast:

This operator is used to modify the const or volatile attributes of the type. In addition to const or volatile modification, type_id and expression are of the same type.

# Include
 
  
Using namespace std; struct Data {int value;}; int main (int argc, _ TCHAR * argv []) {const Data data1 = {10}; // data1.value = 15; // error C3892: "data1": the constant cannot be assigned Data & data2 = const_cast
  (Data1); data2.value = 20; printf ("data1.value = % d data2.value = % d \ n", data1.value, data2.value); const int a = 10; int * B = const_cast
   
    
(& A); * B = 20; printf ("a = % d B = & a is % d \ n", a, B = & ); system ("pause"); return 0 ;}
   
 

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; virtualvoid foo () {}; // the base class must have virtual functions. Dynamic_cast}; class DerivedClass: public BaseClass {public: char * m_szName [100]; void bar (){};}; 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 * PBS = new BaseClass (); DerivedClass * pd21 = static_cast
   
    
(PBS); // parent class-> subclass, static type conversion, dangerous! Access subclass m_szName member out of bounds DerivedClass * pd22 = dynamic_cast
    
     
(); // Parent class-> subclass, dynamic type conversion, secure. The result is NULL.
    
   
  
 

Static_cast:

① It is used to convert the pointer or reference between a base class (parent class) and a derived class (subclass) in the class hierarchy.
It is safe to perform upstream conversion (convert the pointer or reference of a derived class to a base class;
When performing a downstream conversion (converting a base class pointer or reference to a derived class), it is not safe because there is no dynamic type check.
② It is used for conversion between basic data types. for example, convert int to char and convert int to enum. The security of such conversions must also be ensured by developers.
③ Convert a null pointer to a null pointer of the target type. (Int * to long * error C2440: "static_cast": cannot be converted from "int *" to "long *")
④ Convert any type of expression to void type.

Reinterpret_cast:

Reinterpret_cast (Expression)
Type-id must be a pointer, reference, arithmetic type, function pointer, or member pointer. It can convert a pointer to an integer, or an integer to a pointer (convert a pointer to an integer first, and then convert the integer to the original type, you can also obtain the original pointer value)

It is mainly to force the value of the original address to be defined as the new type.

Comparison of reinterpret_cast and static_cast types:

#include 
  
   using namespace std;class A{public:    int m_a;};class B{public:    int m_b;};class C:public A,public B{};int main(int argc, _TCHAR* argv[]){        C* c = new C();    c->m_a = 1;    c->m_b = 2;    A* a1 = static_cast(c);    A* a2 = reinterpret_cast(c);    B* b1 = static_cast
   
    (c);    B* b2 = reinterpret_cast
    
     (c);    printf("c = %p,a1 = %p,b1 = %p\n",c,a1,b1);    printf("c = %p,a2 = %p,b2 = %p\n",c,a2,b2);    printf("a1.m_a = %d, b1.m_b = %d\n",a1->m_a,b1->m_b);    printf("a2.m_a = %d, b2.m_b = %d\n",a2->m_a,b2->m_b);    system("pause");    return 0;}
    
   
  


Running result:

c = 00392950,a1 = 00392950,b1 = 00392954c = 00392950,a2 = 00392950,b2 = 00392950a1.m_a = 1, b1.m_b = 2a2.m_a = 1, b2.m_b = 1

The running result shows that when reinterpret_cast is used for forced conversion, b2 directly starts from the c address and converts c to b2. when static_cast is used, b1 is A shift of an offset of sizeof (A). In other words, it is safe to use static_cast to convert the object pointer of A subclass to A base class object pointer when multiple inheritance occurs. The purpose of reinterpret_cast is to redefine the type, unless you explicitly want to point to the memory to define the target for conversion, otherwise use it with caution.

An example of reinterpret_cast:

# Include
  
   
Using namespace std; typedef void (* FuncPtr) (); typedef int (* FuncPtr2) (); void fun1 () {} int fun2 () {return 10 ;} int main (int argc, _ TCHAR * argv []) {FuncPtr fun [10]; fun [0] = & fun1; // fun [1] = & fun2; // error C2440: "=": cannot be converted from "int (_ cdecl *) (void)" to "FuncPtr" // fun [1] = static_cast
   
    
(& Fun2); // error C2440: "static_cast": cannot be converted from "int (_ cdecl *) (int)" to "FuncPtr" fun [1] = reinterpret_cast
    
     
(& Fun2); // Convert int fun to void fun by force conversion to save FuncPtr2 * pfun = reinterpret_cast
     
      
(& Fun [1]); // when necessary, convert back printf ("run pfun = % d \ n", (* pfun )()); // Print "run pfun = 10" system ("pause"); return 0 ;}
     
    
   
  


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.