• C++ const_cast用法


    const_cast是一种C++运算符,主要是用来去除复合类型中const和volatile属性(没有真正去除)。

    变量本身的const属性是不能去除的,要想修改变量的值,一般是去除指针(或引用)的const属性,再进行间接修改。

    用法:const_cast<type>(expression)

    通过const_cast运算符,也只能将const type*转换为type*,将const type&转换为type&。

    也就是说源类型和目标类型除了const属性不同,其他地方完全相同。

     1 #include<iostream>
     2 using namespace std;
     3 void ConstTest1(){
     4     const int a = 5;
     5     int *p;
     6     p = const_cast<int*>(&a);
     7     (*p)++;
     8     cout<<a<<endl;
     9     cout<<*p<<endl;
    10     
    11 }
    12 void ConstTest2(){
    13     int i;
    14     cout<<"please input a integer:";
    15     cin>>i;
    16     const int a = i;
    17     int &r = const_cast<int &>(a);
    18     r++;
    19     cout<<a<<endl;
    20 }
    21 int main(){
    22     ConstTest1();
    23     ConstTest2();
    24     return 0;
    25 }
    26 输出:
    27 5
    28 6
    29 若输入7
    30 则输出8

    解释为什么输出8:

    当常变量为 const int j =i 时,直接输出j时,编译器不能进行优化,也就是不能够直接用i代替j;

    当常变量为const int j =5时,直接输出j时,编译器会进行优化,也就是用文字常量5直接代替j;

  • 相关阅读:
    HTML和CSS 基本要点必看
    CSS
    六个选择器
    HTML初级课程 (自学可懂)
    this
    1.作用域链
    js if 语句
    js数据类型
    ifelse语句
    三元运算符
  • 原文地址:https://www.cnblogs.com/teng-IT/p/5981294.html
Copyright © 2020-2023  润新知