我使用了一个成员变量,并且在程序的某个点上我想要更改它,但我更喜欢在其他地方“锁定它”,以防止意外的更改。
用于解释的代码:
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
};问题是:它能以某种方式实现吗?像permanent const_cast这样的?
我知道我可以立即使用构造函数初始化列表和常量,但我需要稍后更改我的变量。
发布于 2012-12-14 03:31:18
好的,所有其他我不喜欢的答案,所以我的想法是:隐藏变量。
#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++;
}
};仍然有一些方法可以绕过变量的锁定(比如this->x),但是对于这些情况什么也做不了。
发布于 2012-12-14 03:03:09
class myClass {
int x;
mutable int y;
public:
myclass() : x(1) {}
void foo1 () {x++; y++} // this can change x or y
void foo2 () const { y--; } // this can't change x by can change y
};如果像这样将成员函数标记为const,则不能在该成员中执行任何修改对象成员的操作(除非该成员是mutable或static --而static根本不是对象的成员)。
请注意,这不会简单地阻止您调用试图执行此类修改的函数--相反,标记为const但试图修改对象状态的函数根本不会编译。
然而,我应该补充说,我一点也不相信这真的是最好的设计。相反,在我看来,您对x和y的要求足够复杂,它们作为单独的类直接执行适当的约束可能更有意义(例如,通过为只在正确的环境下接受输入的operator=提供重载)。
换句话说,我在上面展示的mutable的用法(我认为)是对您提出的问题的最简单和最直接的回答,但是您似乎很可能没有真正提出您应该问的问题,并且您更有可能从更改设计中获益--不幸的是,您还没有告诉我们更好的设计可能是什么的“大局”。
发布于 2012-12-14 03:15:17
好吧,我不确定这是否值得你的努力,无论如何,只是为了以防万一这是一个测验或什么,试着把私人继承和朋友结合起来:
class MyClassX {
protected:
MyClassX() : x(1) {}
int x;
public:
int getX() const { return x; } // read only access
};
class MyClassY {
protected:
MyClassY() : y(0) {}
int y;
friend class MyClass;
public:
int getY() const { return y; }
};
class MyClassXY : private MyClassX, private MyClassY {
public:
void foo1 () {x++; y++} // this can change x or y
};
MyClass : public MyClassXY {
public:
void foo2 () const { y--; } // this can't change x but can change y
};https://stackoverflow.com/questions/13866440
复制相似问题