例如,我有两个方法CreateNewDocument和OpenDocument,它们在我的图形用户界面代码中处于两个不同的级别。一个是低级别,它只是方法名称所表示的;另一个是高级别,它将在执行所需的工作之前检查现有文档可能未保存的情况。低级名称出现在高级代码中,因为调用它们是为了实现高级方法。我的问题是,为了不混淆用户和读者,如何区分它们?下面请仔细看一下图解代码。
class GuiClass
{
public:
// Re-implement to tell me how to do the low-level create new document.
virtual void LowLevelCreateNewDocument();
// Then I do the high-level version for you.
void HighLevelCreateNewDocument()
{
// Handle unsavings and blabla...
...
// Then do the low-level version
LowLevelCreateNewDocument();
// Afterward operations
...
}
};发布于 2013-03-16 20:17:50
我会把这个“低级”的CreateNewDocument()方法设为protected或private,因为它看起来只应该分别从该类或派生类中的其他类成员调用。
class GuiClass
{
public:
// Then I do the high-level version for you.
void CreateNewDocument()
{
// Handle unsavings and blabla...
...
// Then do the low-level version
CreateNewDocumentInternal();
}
protected:
//pure virtual to enforce implementation within derived classes.
// |
// V
virtual void CreateNewDocumentInternal() = 0;
};
class GuiClassImpl : public GuiClass
{
protected:
/*virtual*/ void CreateNewDocumentInternal()
{
//Do the low-level stuff here
}
};如果这些方法确实在不同的实现级别上,请考虑将它们放入不同的类或名称空间中,正如前面所建议的那样。对于必须实现纯虚拟的受保护成员函数的子类,您已经有了适当的封装。
https://stackoverflow.com/questions/15448930
复制相似问题