Type conversion Conversion

Source: Internet
Author: User

Arithmetic Conversion)

Integer increase (Integral Promotion)

Pointer Conversion

Convert to bool type

Conversion and enumeration types

Convert to const object

Explicit Conversion

Satic_cast, dynamic_cast, const_cast, and reinterpreter_cast

 

Static_cast:

 Any type conversions implicitly executed by the compiler can be explicitly completed by static_cast.

It is useful to use forced type conversion when a large arithmetic type is assigned to a small type.

Dynamic_cast:

E.g.: Assume that base is a class with at least one virtual function, and the derived class is derived from the base class. if there is a pointer named baseptr pointing to base, it can be forcibly converted to a pointer pointing to derived at runtime like this:

If (derived * derivedptr = dynamic_cast <derived *> (baseptr)

{

// Use derived object to which derivedptr points

}

Else {

// Use the base object to which baseptr points

}

At runtime, if baseptr actually points to the derived object, the conversion is successful, and the derivedptr is initialized to the drived object pointed to by baseptr; otherwise, the conversion result is 0, this means that the derivedptr is set to 0 and the condition in if fails.

Const_cast:

It is used to add or delete the const feature. If you use the const_cast character to perform any other type conversion, compilation errors will occur.

E.g .:

Const char * pc_str;

Char * Pc = string_copy (const_cast <char *> (pc_str ));

Reinterpreter_cast:

It usually provides a lower level of re-interpretation for the bit mode of the operand.

 

Forced conversion of legacy types:

Type (expr); // function-style cast notation

(Type) expr; // C-language-style cast notation.

 

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.