了解成员访问与C++中的继承/友元类

Understanding member access with inheritance / friend class in C++

本文关键字:继承 友元 成员 访问 C++ 了解      更新时间:2023-10-16

摘自C++入门第5版:
看看这些类:

class Base {
    friend class Pal;
public:
    void pub_mem();
protected:
    int prot_mem;
private:
    int priv_mem;
};
class Sneaky : public Base {
private:
    int j;
};
class Pal {
public:
    int f1(Base b){
        return b.prot_mem;  //OK, Pal is friend class
    }
    int f2(Sneaky s){
        return s.j;  //error: Pal not friend, j is private
    }
    int f3(Sneaky s){
        return s.prot_mem; //ok Pal is friend
    }
}

这里 Pal 是 Base 的好友类,而 Sneaky 继承自 Base 并在 Pal 中使用。现在调用s.prot_mem的最后一行,作者给出了它工作的原因,因为 Pal 是 Base 的好友类。但是到目前为止我读到的,我的理解告诉我它应该随时工作,因为 s 派生自 Base,prot_mem是 Base 类的受保护成员,应该已经可以访问 Sneaky,你能解释为什么我错了或更多详细说明吗?

我的理解告诉我,无论如何它都应该有效,因为 派生自基,prot_mem是基类的受保护成员, 应该已经可以访问鬼鬼祟祟

不可以,受保护的变量prot_mem只能由派生类成员访问,而不能由第三方类成员访问,如class Pal,如果Pal不是Base的朋友。

没有友谊,Pal只能看到Sneaky或Base的公众成员。Base的一个成员受到保护这一事实对Pal没有任何好处——它只会使Sneaky受益。

问题是,虽然Sneaky可以访问prot_mem,但您显示的代码不是Sneaky,而是Pal。如果Pal是一个不相关的类,它就无法访问prot_mem,这也在Sneaky中受到保护。但是,PalBase的朋友,这使它具有必要的访问权限。