简体   繁体   English

细粒度访问说明符c ++

[英]Fine grained access specifiers c++

I have the following class :- 我有以下课程: -

class A {
  public:
    // some stuff that everyone should see
  protected:
    // some stuff that derived classes should see
  private:
    // some stuff that only I can see
    void f();
    void g();
};

Now, I want f() to only be accessible from a certain set of classes (say classes B,C,D) and g() to be accessible from a certain other set of classes (say classes D,E,F). 现在,我希望f()只能从一组特定的类(比如类B,C,D)和g()访问,以便可以从某些其他类(例如D,E,F类)访问。 Is there any way to specify this in C++? 有没有办法在C ++中指定它? If I make all the classes friends of A, then both f & g will be accessible from B,C,D,E,F (along with the other private members of A) which is not what I want. 如果我把A的所有班级成为朋友,那么这两个f&g都可以从B,C,D,E,F(以及A的其他私人成员)访问,这不是我想要的。

Is this possible or should I change my object model? 这是可能的,还是应该更改我的对象模型?

class A_f {
    friend class B;
    void f();
};

class A_g {
    friend class C;
    void g();
};

class A: public A_f, public A_g {
    friend class A_f;
    friend class A_g;
private:
    void do_f();
    void do_g();
};

inline void A_f::f() { static_cast<A *>(this)->do_f(); }
inline void A_g::g() { static_cast<A *>(this)->do_g(); }

void B::something(A *a) {
    a->f();
}

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

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