c – 朋友是否看到基类?
发布时间:2020-12-16 03:21:30 所属栏目:百科 来源:网络整理
导读:给出示例代码: 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
给出示例代码:
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; } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- oracle锁表
- 采用Keil4为ARM7 (LPC2103)创建工程 及J-link调试
- ruby-on-rails – 使用Rails迁移删除索引而不知道其名称
- 适用于Xcode 7.3的iOS 10.1平台
- sqlite3 插入数据的时候,返回SQLITE_CONSTRAINT
- AG(聚合端口)
- 在解析XML文件的时候报出异常,应该有为伪属性名!!!
- 103.Which two statements are true regarding the Oracle
- oracle11g – tnsping失败,但可以通过sqlplus连接到Oracle
- React Native Package Manager包管理器介绍