朋友看到基类了吗
Does a friend see base classes?
给定示例代码:
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;
}
};
作为朋友是否能让我获得所有访问权限,就好像我是朋友所在类中的成员函数一样?换言之,我可以攻击基类的受保护和公共成员吗?因为我是朋友,所以基类是私人继承的?
结合David Rodríguez-dribeas和Luchian Grigore的答案:
是的,问题中的例子是有效的,但是,正如David所指出的,受保护的成员不能直接通过基类访问。通过Derived
访问时,您只能访问受保护的成员,通过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;
}
};
friend声明将使MyFriend
有权访问继承关系(对于世界其他地方来说是private
),但不会授予它对受保护的基成员的访问权限,只授予它对公共接口的访问权限。
void MyFriend::test() {
Derived d;
Base & b = d; // Allowed, MyFriend has access to the relationship
b.prot = false; // Not allowed, it does not have access to the base
}
Base
的成员也是Derived
的成员(因为它们不是Base
中的private
)。
相关文章:
- std::具有相同基类的类的变体
- 是否可以初始化不可复制类型的成员变量(或基类)
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 基类中的函数名称解析
- C++初始化基类
- 如何通过派生类函数更改基类中的向量
- 如何定义一个纯抽象基类
- 如何使用基类指针引用派生类成员
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 如果基类包含双指针成员,则派生类的构造函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 为什么此派生对象无法访问基类的后递减方法?
- 公开最直接的基类模板名称
- 当基类是依赖类型时,这是一个缺陷吗
- 朋友功能是否继承?为什么基类朋友功能在派生的类对象上工作
- 递归模板成语如何避免基类是儿童课的朋友
- 在没有朋友的情况下为基类提供受保护的访问权限
- 朋友看到基类了吗