C++ 为什么friend类可以通过派生类访问基类私有数据

C++ 为什么friend类可以通过派生类访问基类私有数据,c++,friend,C++,Friend,这是我第一次在这里发帖 class Base { private: int base; friend class Question; }; class Derived : public Base{ private: int super; }; class Question{ public: void test(Base& base, Derived & derived) {

这是我第一次在这里发帖

class Base {
     private:
         int base;
     friend class Question;
};

class Derived : public Base{
    private:
        int super;
};

class Question{
    public:
        void test(Base& base, Derived & derived)
        {
           int value1 =base.base;  // No problem, because Question is a friend class of base
           int value2 =derived.super; // Compile error, because Question is not a friend class of base
           // Question is here
           int value3 =derived.base;  // No Compile error here, but I do not understand why.
        } 
};

该问题在类问题的最后一行中指出。

friend
适用于该类型的所有成员,无论该类型是否继承。强调这一点:共享的是成员


这意味着您的
问题
类可以访问
Base
的所有成员,这就是
int Base::Base
。它是否通过
Derived
的实例访问此成员无关紧要,因为正在访问的实际成员是在
Base
上声明的,这里没有编译错误,但我不理解为什么
:这是交朋友的初衷,这是为了和他分享你的玩具,因为这个成员仍然属于基类,即使这个实例恰好是一个派生值。通常,静态类型检查就是这样工作的——您可以将派生对象传递给通过引用接受基的函数,并且该函数中的类型检查就像它是基实例一样完成,因为实际类型通常在运行时才知道。