• C++ 修改常量的值


    提示,一般不要修改常量的值,没意义!

    不同的编译器有不同的处理方式。

    特殊的时候才需要考虑:

     1 #include<iostream>
     2 using namespace std;
     3 class A{
     4     const int a;
     5 public:
     6     A(int i):a(i){}
     7     const int& geta()const{
     8         return a;
     9     }
    10 };
    11 int main(){
    12     //这个可以改
    13     A a(10);
    14     cout<<a.geta()<<endl;
    15     const int *b=&(a.geta());
    16     *(int*)((int)b)=20;
    17     cout<<a.geta()<<endl;
    18     
    19     //这个改不了
    20     const int c=10;
    21     const int*d=&c;
    22     *(int*)((int)(d))=20;
    23     cout<<c<<endl;
    24     cout<<*d<<endl;
    25     return 0;
    26 }

    volatile的意义凸显出来:

     1 #include <iostream>
     2 using namespace std;
     3 class B
     4 {
     5 public:
     6     B() { }
     7 public:
     8     int m_iNum;
     9 };
    10 void foo()
    11 {
    12     const B b1;
    13     //b1.m_iNum = 100; //compile error
    14     //上面注释掉的代码编译时会报错,因为b1是一个常量对象,不能对它进行改变;
    15     // 可以做如下转换,体现出转换为指针类型
    16     B *b2 = const_cast<B*>(&b1);
    17     // 或者左侧也可以用引用类型,如果对b2或b3的数据成员做改变,就是对b1的值在做改变
    18     B &b3 = const_cast<B&>(b1);
    19     b2->m_iNum = 200;    //fine
    20     b3.m_iNum = 300;    //fine
    21     cout << b1.m_iNum << endl;
    22     //使用const_cast可以返回一个指向非常量的指针(或引用)指向b1,就可以通过该指针(或引用)对它的数据成员任意改变。
    23 
    24 }
    25 int main( int argc, char * argv[] )
    26 {
    27     foo();
    28     
    29     //const volatile int a = 0; //加上volatile则输出不同 
    30     const int a = 0;
    31     int* b = const_cast<int*>(&a);
    32     *b = 10; //仍然不能修改a 
    33     cout << a << endl;
    34     const_cast<int&>(a) = 10;//仍然不能修改a 
    35     int c = 20;
    36     
    37     cout << "&a = " << &a << endl;
    38     cout << "a = " << a << endl;
    39     cout << "b = " << b << endl;
    40     cout << "c = " << c << endl;
    41     return 0;
    42 }
  • 相关阅读:
    2018QBXT刷题游记(4)
    洛谷 P4302 字符串折叠 题解
    hdu5009 Paint Pearls 题解
    CF467C George and Job 题解
    洛谷P2622 关灯问题II 题解
    洛谷 P3049园林绿化 题解
    洛谷 P1064 金明的预算方案 题解
    洛谷P1979 华容道 题解
    2018QBXT刷题游记(3)
    2018QBXT刷题游记(2)
  • 原文地址:https://www.cnblogs.com/autumoonchina/p/3612419.html
Copyright © 2020-2023  润新知