组合类 C++ 中的封装
我有一个地图类,其中包含一个包含 MapEntity 的向量。 MapEntity是Factory、Farm和其他3个类继承的类。
这 5 个类都应该每隔几秒“勾选”一次,此时它们都会为每个类执行单独的功能,但只有地图类应该能够“勾选”它们。
我如何在 C++ 中支持这种类型的封装?朋友们?我应该只使用公共方法而不是滥用这些方法吗? (尽管我更喜欢适当的封装以实现良好的实践,即使此代码不会被重新分发)。
I have a map class, which contains a vector containing MapEntitys. MapEntity is a class of which Factory, Farm and 3 other classes are inherited from.
These 5 classes both should be "ticked" every few seconds, at which point they will all do a function individual to each class, but only the map class should be able to "tick" them.
How would I support this type of encapsulation in C++? Friends? Should I just use public methods and not misuse the methods? (Although I would prefer proper encapsulation for good practice, even though this code will not be re-distributed).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从语法上讲,你可以使用其中任何一个。
但是,如果要从外部“勾选”MapEntities,则
tick
方法应该是其公共方法的一部分。实际上,它应该是MapEntity类的虚拟公共方法。是的,公共方法是正确的封装。他们告诉你的类的用户它可以做什么。在本例中,用户是
Map
类,它可以tick
MapEntities。仅当
MapEntities
设计仅供Map
使用时,您才应考虑其他解决方案(友元、匿名命名空间等)。Syntactically you could use any of that.
However, if MapEntities are to be "ticked" from outside, the
tick
method should be part of their public methods. Actually, it should be a virtual public method of theMapEntity
class.And yes, public methods are proper encapsulation. They tell the user of your class what it can do. In this case, the user is the
Map
class and it cantick
MapEntities.You should consider other solutions (friends, anonymous namespaces etc.) only if
MapEntities
are designed to be used only byMap
.您可以使用
friend
,但我认为最好不要对可以“勾选”您的 MapEntity 类的内容施加任何限制。在代码中人为限制通常被认为是不好的做法。即使您现在只希望地图类能够调用此函数,但这在将来可能会发生变化。
You could use
friend
, but I think it's better to not put any restriction on what can 'tick' your MapEntity classes.It's generally considered bad practice to put artificial limitations in your code. Even though you only want your map class to be able to call this function right now, this might change in the future.
使用
friend
实际上会降低封装程度,因为您的地图类会看到MapEntities
的任何私有属性,而不仅仅是tick
方法。Using
friend
would actually lower the degree of encapsulation, since your map class would see any privates ofMapEntities
, not only thetick
method.在我看来,您的任务看起来像设计模式访客描述。
客户端代码:
In my opinion your task looks like design-pattern visitor description.
client code: