简体   繁体   English

C ++类设计

[英]C++ class design

Maybe this is not pure c++ technical question, but any advice is highly welcome. 也许这不是纯粹的c ++技术问题,但是任何建议都是值得欢迎的。

I need to implement class with many members (let's say A). 我需要与许多成员一起实施课程(比方说A)。

I also need to access these data by set of other classes and this access should be quite fast (drawing stuff conditioned by members from class A). 我还需要通过其他类的集合来访问这些数据,并且这种访问应该非常快(绘制由A类成员提供的条件)。

First approach was to set access level inside A as private and use kind of setters/getters to get particular elements to check (so many method calls). 第一种方法是将A内部的访问级别设置为私有,并使用种类的设置器/获取器来获取要检查的特定元素(许多方法调用)。

Other approach, just make everything public in A, next one to make dozen of friend classes. 另一种方法是,将所有内容都公开在A中,下一个则创建数十个朋友课程。 To be honest, i do not like any of the above. 老实说,我不喜欢以上任何一个。 Rest of system shouldn't have access to A class members at all, only interested ones. 系统其余部分完全不应该访问A类成员,而只能访问感兴趣的成员。

Maybe someone had to deal with something similar and could advice some good practice, maybe some appropriate design pattern? 也许有人不得不处理类似的事情,并可以建议一些好的做法,也许是合适的设计模式?

If your class is more than a dumb collection of data and flags, the proper approach would be to add whatever you are doing with the data into the class, instead of exposing it with get/set. 如果您的类不仅仅是一个愚蠢的数据和标志集合,那么正确的方法是将您对数据所做的任何事情添加该类中,而不是使用get / set公开它。

For example, if you are pulling coordinates, colors, and line thickness from a class 'Polygon' to draw it, you should instead add a method into the class that does the drawing (and pass the drawing context in as a parameter). 例如,如果要从“多边形”类中提取坐标,颜色和线条粗细以进行绘制,则应在该类中添加一个方法来进行绘制(并将绘制上下文作为参数传递)。

Of the two options I would prefer the getter/setter way, because public members are not a good idea especially if most parts of your system mustn't access these members. 在这两个选项中,我更喜欢使用getter / setter方法,因为公共成员不是一个好主意,尤其是在系统的大多数部分都不能访问这些成员的情况下。
So (even if your question is enough general and greedy of details) if you are worried by "uncontrolled access" maybe a solution could be 因此(即使您的问题足够笼统而又贪婪),如果您担心“不受控制的访问”,也许可以采取一种解决方案

  • declare members private ( at most protected, if base class has some subclass that can access to them) 声明成员为私有 (最多保护,如果基类具有某些可以访问它们的子类)
  • use getters/setters for the members that can be reached by everyone 为每个人都可以使用的成员使用吸气剂/设置器
  • use friend class(or friend methods to access to private/protected members that shouln't be accessed by random classes). 使用好友类(或好友方法来访问私有/受保护的成员,而随机类不应访问该成员)。

Finally, you should try to reduce the amount of different classes accessing to your members, as far as possible,defining a common virtual class in order to provide a common set of valid methods for every subclass. 最后,您应该尝试减少访问成员的不同类的数量,并定义一个公共虚拟类,以便为每个子类提供一组公共的有效方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM