C + + provides four conversion operators

Source: Internet
Author: User

    • Const_cast <new_type> (expression)
    • Static_cast <new_type> (expression)
    • Reinterpret_cast <new_type> (expression)
    • dynamic_cast <new_type> (expression)

They have the same structure and look like a template method. These methods are provided to developers to use for pointers and reference conversions.

1. Const_cast Usage

Const_cast is a C + + operator that is primarily used to remove the const and volatile attributes in a composite type (no real removal).

The Const property of the variable itself cannot be removed, and to modify the value of the variable, it is generally to remove the const attribute of the pointer (or reference) and then modify it indirectly.

Usage:const_cast<type> (expression)

With the const_cast operator, you can only convert the const type* to type* and convert the const type& to type&.

This means that the source and destination types are identical except for the const attribute.

#include <iostream>using namespacestd;voidConstTest1 () {Const intA =5; int*p; P= const_cast<int*> (&a); (*P) + +; cout<<a<<Endl; cout<<*p<<Endl; }voidConstTest2 () {inti; cout<<"Please input a integer:"; CIN>>i; Const intA =i; int&r = const_cast<int&>(a); R++; cout<<a<<Endl;}intMain () {ConstTest1 ();    ConstTest2 (); return 0;} Output:56Output 8 If input 7

Explain why output 8:

When the constant variable is a const int J =i, the compiler cannot optimize the direct output J, that is, I can not be used directly instead of J;

When the constant variable is const int j = 5 o'clock, when the direct output J, the compiler will be optimized, that is, the literal constant 5 directly instead of J;

C + + provides four conversion operators

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.