给出示例代码:
class Base { public: bool pub; protected: bool prot; }; class Derived : private Base { friend class MyFriend; }; class MyFriend { Derived _derived; void test() { // Does standard provide me access to _derived.pub and _derived.prot? cout << "Am I allowed access to this: " << _derived.pub << " and this: " << _derived.prot; } };
做朋友会给我所有的访问权限,我会得到好像我是班级中的一员,我是他的朋友吗?换句话说,由于我是朋友,我可以获得私人继承的基类的受保护和公共成员吗?
解决方法
结合DavidRodríguez的答案 – dribeas和Luchian Grigore:
是的,问题中的示例可行,但正如David指出的那样,受保护的成员无法通过基类直接访问.只有通过Derived访问时才能访问受保护的成员,当通过Base访问时,您无权访问相同的成员.
换句话说,base的受保护成员被视为派生的私有成员,因此朋友可以看到它们,但是,如果你投射到基类,没有朋友关系,因此受保护的成员不再无障碍.
这是一个澄清差异的例子:
class MyFriend { Derived _derived; void test() { bool thisWorks = _derived.pub; bool thisAlsoWorks = _derived.prot; Base &castToBase = _derived; bool onlyPublicAccessNow = castToBase.pub; // Compiler error on next expression only. // test.cpp:13: error: `bool Base::prot' is protected bool noAccesstoProtected = castToBase.prot; } };
原文地址:https://www.jb51.cc/c/111770.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。