C ++ const公共字段与getter方法 [英] c++ const public field vs. a getter method
问题描述
我想向特定类的每个对象添加唯一ID(在单个会话中)。一种解决方案是使用工厂函数来增加一些静态计数器。一个简单的解决方案是将该计数器添加到类本身,例如:
I want to add unique ID (within a single session) to each object of a certain class. One solution is to use a factory function which increments some static counter. A simpler solution is to add this counter to the class itself, e.g.:
class fooWithUniqueId {
public:
fooWithUniqueId() : id(next_id++) {...};
long id;
private:
static long next_id = 0;
}
但是,缺陷在于 id
字段是公共的,并且可以被调用方更改,从而违反了其唯一性。传统的方法(至少在我看来是这样)是将 id
设为私有,并使用getter函数对其进行访问,因此:
A flaw, however, is that the id
field is public, and can be changed by the caller, thus violating its uniqueness. A traditional (well, at least in my eyes) is to make id
private, and use a getter function to access it, thus:
class fooWithUniqueId {
public:
fooWithUniqueId() : id(next_id++) {...};
long getId() const { return id; };
private:
long id;
static long next_id = 0;
}
但是我正在考虑采用另一种方法。我可以将id设为const公共类字段:
But I'm considering a different approach. I can make id a const public class field:
class fooWithUniqueId {
public:
fooWithUniqueId() : id(next_id++) {...};
const long id;
private:
static long next_id = 0;
}
我更喜欢这种方式,因为我不必一直打电话给 getId()
每次需要ID时,都可以将其用作映射中的键(因为复制构造正确初始化了复制对象的ID)。我可以想到的一个缺点是,尽管目前不需要此功能,但我无法在 fooWithUniqueId
对象之间实现分配。
I like this way better because I don't have to keep calling getId()
each time I need the id, I can use the id as a key in a map (as copy construction correctly initializes the id of the copy object). One disadvantage I can think of is that I cannot implement assignments between fooWithUniqueId
objects, although currently I do not need this feature.
- 每种方法(getter函数/ const字段)的优缺点是什么?
- 假设我使用的是'const'方法,以后是否可以在不破坏代码的情况下实现赋值运算符?
谢谢,波阿斯(Boaz)
Thanks, Boaz
推荐答案
我可以将id用作地图中的键(正确构建副本初始化复制对象的ID)
I can use the id as a key in a map (as copy construction correctly initializes the id of the copy object)
正确是什么意思?无论是存储在私有变量还是公共成员变量中,默认的复制构造函数都会复制该ID,最后您将获得两个共享相同ID的对象。
What do you mean by "correctly"? The default copy constructor will copy the ID, whether it is stored in a private or a public member variable, and you will end up with two objects sharing the same ID. This might not be what you want.
通常,您永远不要在C ++中使用公共变量,因为它违反了正确的封装。始终使用( inline
)getter方法。唯一的缺点是您必须再输入几个字符。
In general, you should never use public variables in C++ as it violates proper encapsulation. Always use a (inline
) getter method. The only disadvantage is that you have to type a few more characters.
我强烈建议您遵循最佳做法,并使用带有getter函数的私有字段。
I strongly suggest that you stick to best practices and use a private field with a getter function.
这篇关于C ++ const公共字段与getter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!