简体   繁体   English

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

[英]Understanding member access with inheritance / friend class in C++

from C++ primer 5th edition: 来自C ++入门第5版:
have a look at these classes: 看看这些类:

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
    }
}

Here Pal is a friend class of Base, while Sneaky inherits from Base and is used in Pal. Pal是Base的朋友类,而Sneaky继承自Base,用于Pal。 Now the very last line where s.prot_mem is invoked, author gives the reason it works because Pal is a friend class of Base. 现在是调用s.prot_mem最后一行,作者给出了它起作用的原因,因为Pal是Base的朋友类。 But what i read so far, my understanding tells me that it should work anywawy, because s derives from Base and prot_mem is protected member of Base Class, which should have already access to Sneaky, can you explain why i am wrong or some more elaboration please? 但到目前为止我读到的内容,我的理解告诉我它应该可以工作,因为s派生自Base,而prot_mem是Base Class的受保护成员,它本应该已经访问Sneaky,你能解释为什么我错了或者更详细一些请?

my understanding tells me that it should work anyway, because s derives from Base and prot_mem is protected member of Base Class, which should have already access to Sneaky 我的理解告诉我它应该工作,因为s派生自Base,prot_mem是Base Class的受保护成员,它应该已经访问Sneaky

No, protected variable prot_mem can only be accessed by derived class member, but not by third party class member, like class Pal , if Pal is not a friend of Base . 不,受保护的变量prot_mem只能由派生类成员访问,但不能由第三方类成员访问,如class Pal ,如果Pal不是Base的朋友。

Without friendship, Pal only sees Sneaky or Base's public members. 如果没有友谊, Pal只会看到Sneaky或Base的公众成员。 The fact that one member of Base is protected does not benefit Pal in any way - it only benefits Sneaky . Base一名成员受到保护这一事实不会以任何方式使Pal受益 - 它只Sneaky受益。

The thing is that while Sneaky can access prot_mem , the code you're showing is not in Sneaky , it's in Pal . 事情是,虽然Sneaky可以访问prot_mem ,但你所展示的代码并不是在Sneaky ,而是在Pal If Pal was an unrelated class, it couldn't access prot_mem , which is also protected in Sneaky . 如果Pal是一个不相关的类,它就无法访问prot_mem ,它在Sneaky也受到保护。 However, Pal is a friend of Base , which gives it the access necessary. 但是, PalBase的朋友,它为其提供了必要的访问权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM