Access private elements of object of same class

孤人 提交于 2019-12-30 03:20:07

问题


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

class Foo
{
    friend class Foo;
}

回答1:


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.




回答2:


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.




回答3:


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

warning: class ‘Foo’ is implicitly friends with itself



回答4:


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



来源:https://stackoverflow.com/questions/3832613/access-private-elements-of-object-of-same-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!