C ++类设计问题 [英] C++ class design questions
问题描述
我有一个类Node。此类可以添加或删除与其自身相关的其他节点。节点由List类使用。为了防止节点在使用期间直接(在外部,而不是由适当的类)修改,并导致List类出现问题,节点添加/删除功能是受保护的或私有的。这需要List类是Node的朋友。
I have a class Node. This class can add or remove other nodes relative to itself. Node is used by a List class. To prevent the nodes being modified directly (externally, IE not by the appropriate classes) during usage and causing problems with the List class, the nodes add/remove functions are either protected or private. This requires that List class is a friend to Node.
但是,这个问题是List类本身是其他子类的模板类,添加原型/为每个子类添加friend关键字显然不是最好的解决方案。
However, the problem with this is that the List class itself is a template class for other subclasses, and adding prototyping/adding the friend keyword for each subclass is clearly not the best solution.
我如何设计Node和List类/子类,以便:
How would I design the Node and List class/subclasses so that:
- 节点不能由外部构造,只用特定的类/子类构造?
- 节点可以构造/删除其他节点
- 节点函数只能访问特定类(列表,列表子类和列表辅助类 - 列表帮助类不是列表的子类)?
- 列表,列表子类和列表辅助类可以直接修改或间接修改Node的非公开变量 / li>
- Node cannot be constructed by itself externally, is only constructed with specific classes/subclasses?
- Node can construct/remove other nodes given above?
- Node functions are only accessible to specific classes (List, list subclasses, and list helper classes - list helper classes are not subclasses of list)?
- The node variable (Item) is publicly accessible give above?
- List, list subclasses and list helper classes can directly modify or indirectly modify the non-public variables of Node?
这些是否可能,如果可能,如何?
Are these possible, and if so, how?
推荐答案
我会使 Node
一个受保护的嵌套类列表
:
I would make Node
a protected nested class of List
:
class List
{
...
protected:
class Node
{
...
};
};
这样,只有List和它的子类可以访问它。 由于它嵌套在它还有助于突出两个类之间的函数关系。 List
中,list可以访问其私有/ protected成员和函数。
This way, only List and its subclasses can access it. Since it is nested within It also helps to highlight the functional relationship between the two classes. This probably takes care of all your dot points except the third.List
, list may access its private/protected members and functions.
编辑仔细检查我的事实,看起来在C ++封装类不要拥有对嵌套类成员的特殊访问权限(看起来是一个Java东西),请参阅此处。因此,您需要使节点
成员公开,但我仍然认为此解决方案鼓励良好的封装。
EDIT double checking my facts, it seems that in C++ enclosing classes do not have special access permissions to nested class members after all (seems that's a Java thing), see here. As such, you will need to make Node
members public, but I still think this solution encourages good encapsulation.
这篇关于C ++类设计问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!