Clause 2. It is best to use C + + transformation operators

Source: Internet
Author: User

C + + provides four cast operators:static_cast,const_cast,dynamic_cast and reinterpret_cast.

1. static_cast

    • Used to convert between basic type values, for example: int---char, and security is controlled by the programmer.
    • cannot be used for conversions between pointers between unrelated types, for example: int*---double* compilation error.
    • Pointers–other NULL to pointers.
    • A pointer or reference transformation between a base class and a derived class. Up-casting (a pointer or reference to a pointer or reference to a base class) is safe, and down-casting (a pointer or reference that converts a base-class pointer or reference to a subclass) is unsafe.

2. const_cast

    • A constant class object (or primitive type) is not supported for conversion to a non-Const class object (or base type).
    • The constant pointer is converted to a very variable pointer, and the converted pointer points to the original.
    • A constant reference is converted to a very literal reference.

3. dynamic_cast

    • For inheritance relationships, only class object pointers and referenced class conversions are supported.
    • Casts a base class object pointer (or reference) to an inherited class pointer and reference, and dynamic_cast handles it according to whether the translated pointer or reference really points to an inherited class pointer or reference. Conversion between pointers fails, returns NULL, reference conversion fails, throws an exception.
    • The downstream conversion of a pointer or reference is premised on a virtual function of the base class.

4. reinterpret_cast

    • does not have portability.
    • Used primarily to convert function pointers.

 

Clause 2: It is best to use C + + transformation operators

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.