可以锁定变量以防止在c ++中对其进行更改吗?

Pet*_*etr 6 c++ variables const

我正在使用一个成员变量,并且在程序的某个时刻我想要更改它,但我更喜欢在其他地方"锁定"以防止意外更改.

代码解释:

class myClass {
    int x;  // This should be prevented to being changed most of the time
    int y;  // Regular variable
    myclass() {x = 1;}
    void foo1 () {x++; y++;} // This can change x
    void foo2 () {x--; y--;} // This shouldn't be able to change x
                             // I want it to throw a compile error
};
Run Code Online (Sandbox Code Playgroud)

问题是:能以某种方式实现吗?像永久const_cast这样的东西?

我知道我可以立即使用构造函数初始化列表和常量,但我需要稍后更改我的变量.

Moo*_*uck 2

好吧,我不喜欢所有其他答案,所以这是我的想法:隐藏变量。

#define READONLY(TYPE, VAR) const TYPE& VAR = this->VAR //C++03
#define READONLY(VARIABLE) const auto& VARIABLE = this->VARIABLE //C++11

class myClass {
    int x;  // This should be prevented to being changed most of the time
    int y;  // Regular variable
    myClass() :x(1), y(2) {}
    void foo1 () {// This can change x
        x++; 
        y++;
    } 
    void foo2 () {// This shouldn't be able to change x
        READONLY(x); //in this function, x is read-only
        x++; //error: increment of read-only variable 'x'
        y++;
    } 
};
Run Code Online (Sandbox Code Playgroud)

仍然有一些方法可以绕过变量的锁定(例如this->x),但对于这些情况无能为力。