公共静态const变量是否破坏了封装意识形态? [英] Does a public static const variable break the encapsulation ideology?
问题描述
我总是在为类中的值是否应该为 static
和 const
的决定而苦恼
I always seem to struggle with the decision of whether a value in a class which should be static
and const
should be public or private with a static public method for access.
class DeepThought
{
public:
static const int TheAnswer = 42;
};
对比:
class DeepThought
{
public:
static int GetTheAnswer() { return TheAnswer; }
private:
static const int TheAnswer = 42;
};
我想要以第一种方式进行操作,但位于我内心深处即使它的值不变,也感觉它破坏了封装。第二种方法似乎似乎并没有真正在表中添加任何东西,并且不必要地使代码混乱。
I want to do it the first way, but somewhere deep inside me feels like it breaks encapsulation even though its a constant value. The second way just seems like it doesn't really add anything to the table though and needlessly clutters up the code.
所以我问,这两者之间有什么本质上的错误吗
So I ask, is there anything fundamentally wrong with either choice and if so, what?
推荐答案
从纯粹的理论意义上讲,第二种选择更为正确。在实际意义上,我同意您的观点-用getter函数包装常数值是没有用的,而且无论如何都会被编译器删除。
In a purely theoretical sense, the second option is the more correct. In the practical sense, I agree with you - wrapping the constant value with a getter function is useless and will be removed by the compiler anyway.
根据我的经验,有时
最后一点要注意的是,我们以前通常使用枚举:
And a final note - we used to use enums for this:
enum CONSTS
{
TheAnswer = 42,
};
这篇关于公共静态const变量是否破坏了封装意识形态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!