【问题标题】:How can/should C++ static member variable and function be hidden?如何/应该隐藏 C++ 静态成员变量和函数?
【发布时间】:2010-11-11 03:48:28
【问题描述】:

m_MAX 和 ask() 由 run() 使用,但不应公开。如何/应该这样做?

#include <vector>
class Q {
public:
    static int const m_MAX=17;
    int ask(){return 4;}
};
class UI {
private:
    std::vector<Q*> m_list;
public:
    void add(Q* a_q){m_list.push_back(a_q);}
    int run(){return Q::m_MAX==m_list[0]->ask();}
};
int main()
{
    UI ui;
    ui.add(new Q);
    ui.add(new Q);
    int status = ui.run();
}

【问题讨论】:

    标签: c++ c++11 encapsulation


    【解决方案1】:

    您可以在类 Q 的私有部分中定义 m_MAX 和 ask()。然后在 Q 中添加:“朋友类 UI”。这将允许 UI 访问 Q 的私有成员,但不能访问其他成员。另请注意,UI 必须在“朋友类 UI”语句之前定义。前向声明将起作用。

    【讨论】:

    • 将 Q 更改为:class Q { private: static int const m_MAX=17; int ask(){return 4;} 好友类 UI; };没有产生错误。您如何注意前向声明适用?
    • 嗯,也许我错了,我以为你会得到一个未知符号错误。但也许朋友声明就像一个前向声明。不过很好用。
    【解决方案2】:

    一个简单的解决方案 - 将 m_MAX 和 ask() 设为私有,并使 UI 成为 Q 的朋友。

    【讨论】:

      【解决方案3】:

      是的,将 UI 声明为 Q 的朋友就是您所问问题的答案。另一种解决方案是让 Q 成为 UI 的私有嵌套类:

      #include <vector>
      
      class UI {
      private:
          class Q {
          public:
              static int const m_MAX=17;
              int ask(){return 4;}
          };
      
          std::vector<Q*> m_list;
      
      public:
          void addNewQ(){m_list.push_back(new Q);}
          int run(){return Q::m_MAX==m_list[0]->ask();}
      };
      
      int main()
      {
          UI ui;
          ui.addNewQ();
          ui.addNewQ();
          int status = ui.run();
      }
      

      现在,Q 的任何内容在 UI 之外都是可见的。 (这可能是也可能不是你想要的。)

      【讨论】:

        【解决方案4】:

        最简单的解决方案是从类中删除m_MAX,并将其放入定义Q::askUI::run.cpp 文件中的anonymous namespace。由于它是static const,因此将其作为类声明的一部分将一无所获。

        【讨论】:

          猜你喜欢
          • 2010-12-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-13
          相关资源
          最近更新 更多