C++中修改常量值的方法

1.无法对全局常量,静态常量重新赋值,会引发编译错误或者运行时错误

2.对函数内的局部常量可以重新赋值,但是并不会改变值,只是不会报错,所以没什么卵用

3.可以对类中的成员常量进行重新赋值,主要的方法就是通过获取原常量的底层常量指针,使用强制类型转换,将常量指针改变成非常量指针,然后通过非常量指针进行赋值。例子如下

class AClass{
private:
    const int x;
    int *const array;

public:
    AClass(int n):array(new int[n]),x(n){}

    void changeConst(int m){
        *(int *)&x=m;
        *(const_cast(&x))=m;
        //*(static_cast(&x))=m;这个是不行的,因为static_cast无法修改底层const,上面两个都行;
        if(array)
        delete [] array;
        *(int **)&array=new int[m];
    }
}

你可能感兴趣的:(c++,c++)