简体   繁体   English

如何/应该如何隐藏C ++静态成员变量和函数?

[英]How can/should C++ static member variable and function be hidden?

m_MAX and ask() are used by run() but should otherwise not be public. m_MAX和ask()由run()使用,但否则不应公开。 How can/should this be done? 如何/应该这样做?

#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();
}

You could define both m_MAX and ask() within the private section of class Q. Then in Q add: "friend class UI". 您可以在类Q的私有部分中定义m_MAX和ask()。然后在Q中添加:“ friend class UI”。 This will allow UI to access the private members of Q, but no one else. 这将允许UI访问Q的私有成员,但不能访问其他成员。 Also note that UI must be defined before the "friend class UI" statement. 另请注意,必须在“朋友类UI”语句之前定义UI。 A forward declaration will work. 向前声明将起作用。

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

Yep, declaring UI as friend of Q is the answer to what you ask. 是的,将UI声明为Q的朋友就是您所要求的答案。 An alternative solution could be to make Q a private nested class of UI: 一种替代解决方案是使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();
}

Now, nothing of Q is visible outside UI. 现在,在UI外部看不到Q。 (Which may or may not be what you want.) (可能不是您想要的。)

The simplest solution would be to remove m_MAX from the class and put it in an anonymous namespace in the .cpp file in which both Q::ask and UI::run are defined. 最简单的解决方案是从类中删除m_MAX ,并将其放在.cpp文件中的匿名namespace中,该文件中同时定义了Q::askUI::run Since it's a static const you gain nothing by having it as part of the class declaration. 由于它是static const ,因此将其作为类声明的一部分不会获得任何好处。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM