Access private elements of object of same class

后端 未结 4 421
无人及你
无人及你 2020-12-31 20:45

Is this legal? If not, will the following code allow this?

class Foo
{
    friend class Foo;
}
4条回答
  •  爱一瞬间的悲伤
    2020-12-31 21:17

    That's redundant. Foo already has access to all Foo members. Two Foo objects can access each other's members.

    class Foo {
    public:
      int touchOtherParts(const Foo &foo) {return foo.privateparts;}
    private:
      int privateparts;
    };
    
    Foo a,b;
    b.touchOtherParts(a);
    

    The above code will work just fine. B will access a's private data member.

提交回复
热议问题