Type conversions in C + +

Source: Internet
Author: User
Tags volatile

in the C + + language, there are two types of type conversions: implicit type conversions and explicit type conversions.

1. Implicit type conversions

Implicit conversions are the system's default transformations that do not need to be declared . In general, the conversion of data types is usually done automatically by the compilation system and does not require manual intervention, so it is called an implicit type conversion.

Implicit conversions are performed in the following four scenarios:

1: In arithmetic expressions, low types can be converted to high types.
2: In an assignment expression, the value of the right-hand expression is automatically converted to the type of the left variable;
3: When an argument is passed in a function call, the system implicitly converts the argument to the type of the formal parameter and assigns the parameter.
4: When the function has a return value, the system implicitly converts the return expression type to the return value type and assigns the value to the calling function.

int    0 ; Double Ten  = itmp;  // Itmp is implicitly converted to double if (itmp);        // Itmp is implicitly converted to boolitmp + dtmp; // The result of the calculation is implicitly converted to double

  

2. Display Type conversions

2.1 Legacy Type Conversions

The legacy type conversion is actually a C-style conversion, which is inherited from the C language, for example, in order to convert a floating-point number of type Doubole to an integer:

int i; Double  = (int) D; or int  i; Double  int(d);

2.2 C + + new type conversion

The above two methods do not apply to classes (class) and class pointers in C + +, the best solution is not to use the C-style coercion type conversion, but instead use the standard C + + type conversion character: Static_cast, dynamic_cast. There are four new type conversions in standard C + +: static_cast, dynamic_cast, reinterpret_cast, and const_cast.

dynamic_cast

dynamic_cast is primarily used for pointers and references to objects. when used with a polymorphic type, it converts a reference or pointer of the base class type object to another type of reference and pointer in the same inheritance hierarchy.

conversion format for dynamic_cast:dynamic_cast< type> (expression)

The operator converts expression to an object of type types. The type must be a pointer to a class, a reference to a class, or a void*, and if type is a pointer to a class, expression must also be a pointer, and if type is a reference, then expression must be a reference.

If expression is the base class of type, when converted using dynamic_cast, the runtime checks to see if expression really points to an object of type types, and if so, the correct conversion to get the corresponding value; otherwise null is returned. If it is a reference, an exception will be thrown at run time. For example:

classA {Virtual voidf () {};  }; classD | PublicA {Virtual voidf () {};  }; voidMain () {A* PA =NewB//A * PA2 =NewA; B* PB = dynamic_cast<b*> (PA);//Ok:pa actually points to a Bb* PB2 = dynamic_cast<b*> (PA2);//PA2 points to a no a B, now PA2 is NULL}

static_cast

Conversion format for static_cast:static_cast< type > (expression)

The operator converts expression to type, but there is no run-time type check to guarantee the security of the conversion. It is mainly used in the following ways:

① is used for the conversion of pointers or references between base and subclass classes in a class hierarchy.

It is safe to make an upstream conversion (a pointer or reference to a class is converted to a base class representation).

When a downstream conversion (a base class pointer or reference is converted to a subclass representation) is not secure because there is no dynamic type checking.

② is used for conversions between basic data types. convert int to char, convert int to enum. The security of this conversion is also to be ensured by the developer.

③ converts a null pointer to a null pointer of the target type.

④ converts any type of expression to a void type.

Note: static_cast cannot convert the const, Volitale, or __unaligned properties of expression.

Reinpreter_cast

reinpreter_cast Conversion Format reinpreter_cast<type> (expression)

Reinterpret_cast is a highly dangerous conversion, which is merely a re-interpretation of the bits. This operator can be converted between non-related types. The result of the operation is simply a binary copy of the value from one pointer to another pointer. Content that is pointed to between types does not have any type of check and conversion. Cases:

class a{}; class b{}; Anew  A; b* b = reinpreter_cast<b*> A;

Const_cast

const_cast Conversion Format:const_cast<type> (expression)

the operator is used to modify the const or volatile properties of a type. Type and expression are the same types except for const or volatile adornments. The constant pointer is converted to a very pointer, and still points to the original object, the constant reference is converted to a very literal reference and still points to the original object, and the constant object is converted to a very mass object.

#include <iostream>using namespacestd; classCA { Public: CA (): M_ia (Ten){}      intM_ia;  }; intMain () {ConstCA *pa =NewCA; //Pa->m_ia = +;//error is now assigned to M_ia via PA because the Const propertyCA *PB = Const_cast<ca *>(PA); PB->m_ia = -; //now PA and PB point to the same object, can be modified by PB M_iacout << Pa->m_ia <<Endl; cout<< Pb->m_ia <<Endl; //-------------------------------------//    ConstCA &a = *PA; //A.m_ia = $;//ErrorCA &b = Const_cast<ca &>(a); B.m_ia= $; //both A and B are now references to the same object, which can be modified by B M_iacout << B.m_ia <<Endl; cout<< A.m_ia <<Endl; }

Type conversions in C + +

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.