【发布时间】:2012-12-01 17:34:12
【问题描述】:
我正在使用一个成员变量,并且在程序的某个时刻我想更改它,但我更喜欢在其他任何地方“锁定”它以防止意外更改。
代码解释:
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
};
问题是:能以某种方式实现吗?像永久 const_cast 之类的东西?
我知道我可以立即使用构造函数初始化列表和常量,但我需要稍后更改我的变量。
【问题讨论】:
-
将其设为私有,并且仅在需要时更改?
-
你想阻止实现改变x,还是想阻止任何人调用该方法?
-
@Joe:我想在编译时抛出一个错误。
-
void foo2 () const {x--;} -
如果你不想这么做,为什么
foo2完全修改x?