从特定类访问特定的私有成员

Access to specific private members from specific class

本文关键字:成员 访问      更新时间:2023-10-16

我有一个class

class A
{
.....
private:
    int mem1;
    int mem2;
}

我有另一个类B,它只需要访问mem1。

class B
{
  ....
}

如何只能从类B访问私有成员mem1 ?我不想用朋友。这意味着可以访问所有私有成员。

通过对class A进行一些重新排列(这可能不一定是可接受的),您可以实现以下目标:

class Base
{
    friend class B;
    int mem1;
};
class A : public Base
{
    int mem2;
};

这利用了friend ship不能通过继承传递的事实。

则对于class B

class B
{
    void foo(A& a)
    {
        int x = a.mem1; // allowed
        int y = a.mem2; // not allowed    
    }
};

可以编写成员为mem1和友元为B的基类

class Base {
   protected:
   int mem1;
   friend class B;
};
class A: private Base {
  // ...
};