开发者

C++ Friend Classes

Just trying to make sure I have understood friends properly with this one

class A
{
  friend class B;
  int valueOne;
  int valueTwo;
  public:
  int GetValueOne(){ return valueOne; }
}
class B
{
  public:
  A friendlyData;
  int GetValueTwo(){ return friendlyData.valueTwo; }
}
main()
{
  B myObject;
  myObject.friendlyData.GetValueOne(); // OK?
  myObject.GetValueTwo(); // OK?
}

In reference to that code about, if we ignore the lack of initialising, the two functions in main would OK right? And besides doing some funky stuff, their should be no other way to get the data from these classes... To the out side of these class, B.A has 开发者_如何学编程no accessible data, just the member function.


Yes the two identified calls in main are OK. They involve the access of 3 members: B::A, B::GetValueTwo and A::GetValueOne. All of which have publicaccessibility and expose no privae types. Hence they're usable from anywhere including main.


It looks reasonable as both of the GetValueX methods are public and so the calls are fine. The call to GetValueTwo() call makes use of its friendship.

Word of warning: friendship can break the encapsulation in your design.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜