C++ - Friend友元能继承吗

来源:互联网 发布:免费医疗软件 编辑:程序博客网 时间:2024/05/01 03:36

友元不能被继承:即,基类的友元未必是子类的友元;某类型的友元的子类未必是此类型的友元。

详细的,可以看以下两节:

What does it mean that "friendship isn't inherited, transitive, or reciprocal"?

Just because I grant you friendship access to me doesn't automaticallygrant your kids access to me, doesn't automatically grant your friendsaccess to me, and doesn't automatically grant meaccess to you.

  • I don't necessarily trust the kids of my friends. The privileges offriendship aren't inherited.Derived classes of afriend aren't necessarilyfriends. Ifclass Fred declares that classBase is afriend,classesderived from Base don't have any automatic specialaccess rights toFred objects.
  • I don't necessarily trust the friends of my friends. The privilegesof friendship aren't transitive. Afriend of a friend isn't necessarily afriend. Ifclass Fred declares classWilma as a friend, andclassWilma declaresclass Betty as a friend,class Betty doesn'tnecessarily have any special access rights to Fred objects.
  • You don't necessarily trust me simply because I declare you myfriend. The privileges of friendship aren't reciprocal. Ifclass Freddeclares thatclass Wilma is afriend, Wilma objects have specialaccessto Fred objects butFred objects do not automatically have special accessto Wilma objects.
(http://www.parashift.com/c++-faq-lite/friends.html)

What is inherited from the base class?

In principle, a derived class inherits every member of abase class except:

  • its constructor and its destructor
  • its operator=() members
  • its friends
(http://www.cplusplus.com/doc/tutorial/inheritance/)