首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不同的层次命名相似的方法?

如何在不同的层次命名相似的方法?
EN

Stack Overflow用户
提问于 2013-03-16 19:52:25
回答 1查看 94关注 0票数 2

例如,我有两个方法CreateNewDocument和OpenDocument,它们在我的图形用户界面代码中处于两个不同的级别。一个是低级别,它只是方法名称所表示的;另一个是高级别,它将在执行所需的工作之前检查现有文档可能未保存的情况。低级名称出现在高级代码中,因为调用它们是为了实现高级方法。我的问题是,为了不混淆用户和读者,如何区分它们?下面请仔细看一下图解代码。

代码语言:javascript
复制
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
        ...
    }
};
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-16 20:17:50

我会把这个“低级”的CreateNewDocument()方法设为protectedprivate,因为它看起来只应该分别从该类或派生类中的其他类成员调用。

代码语言:javascript
复制
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
    }
};

如果这些方法确实在不同的实现级别上,请考虑将它们放入不同的类或名称空间中,正如前面所建议的那样。对于必须实现纯虚拟的受保护成员函数的子类,您已经有了适当的封装。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15448930

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档