这是一个困扰我一段时间的问题,但我无法找到最好的解决方法。我打算通过一个例子来说明。
我正在开发一个带有许多类的图形库。其中一些类之间存在“部分”关系,就像这3个类:
namespace MyGraphicsLibrary
{
class MatrixStack
{
};
class Transform
{
MatrixStack mMatrixStack;
};
class Renderer
{
Transform mTransform;
};
}
Renderer
类是供用户使用的,但我不希望他们在查找 MyGraphicsLibrary
时看到 Transform
、MatrixStack
类。最后两个类只适用于 Renderer
类,而不适用于用户使用。
这里我想做两件事:
隐藏
Transform
、MatrixStack
类,使其对用户不可见。反映类的“部分-整体”层次结构。
为了解决这个问题,我尝试了以下方法:
The best solution for me would be the private nested-classes, as it would show the user that the nested class is private and also reflects the hierarchy if you simply look at the
Renderer
class declaration. The following post actually makes me uncertain that is good solution: Pros and cons of using nested C++ classes and enumerations?I tried to put
Transform
,MatrixStack
into another namespace calledPrivate
. So user looking upMyGraphicsLibrary
namespace would seePrivate
namespace only covering all classes which are not for the users. That's good, but there are lot of other classes with the same issue, and i quickly fill thePrivate
namespace with classes which has nothing to do with each other. Here I could only come up with ugly solutions, like introducing nested namespaces:namespace MyGraphicsLibrary { //private classes belonging to Renderer class namespace PrivateRenderer { class MatrixStack { }; class Transform { MatrixStack mMatrixStack; }; } //public classes for users class Renderer { Transform mTransform; }; }