开发者

Access private elements of object of same class

开发者 https://www.devze.com 2023-01-18 18:36 出处:网络
Is this legal? If not, will the following code allow t开发者_如何转开发his? class Foo { friend class Foo;

Is this legal? If not, will the following code allow t开发者_如何转开发his?

class Foo
{
    friend class Foo;
}


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.


Yes it is legal for an object of class Foo to access the private members of another object of class Foo. This is frequently necessary for things like copy construction and assignment, and no special friend declaration is required.


It is redundant and unnecessary. Moreover, I get the following warning in g++

warning: class ‘Foo’ is implicitly friends with itself


Classes friending themselves makes sense if they're templates, as each instantiation with distinct parameters is a different class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号