简体   繁体   中英

Access to specific private members from specific class

I have a class

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

I have another class B which need to access only to mem1.

class B
{
  ....
}

How can I access private member mem1 from only from class B? I don't want to use friend. This means access to all private members.

With some rearrangement to class A (which might not necessarily be acceptable), you can achieve this:

class Base
{
    friend class B;
    int mem1;
};

class A : public Base
{
    int mem2;
};

This exploits the fact that friend ship is not transitive through inheritance.

Then, for class B ,

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

You can write a base class with member mem1 and friend B

class Base {
   protected:
   int mem1;
   friend class B;
};

class A: private Base {
  // ...
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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