c++ - 为什么friend类可以通过Derived类访问到Base类私有(private)数据

标签 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)
        {
           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 适用于该类型的所有成员,无论该类型是否被继承。强调这一点:共享的是成员

这意味着您的 Question 类可以访问 Base 的所有成员,也就是 int Base::base。它是否通过 Derived 的实例访问该成员是无关紧要的,因为被访问的实际成员是在 Base 上声明的。

关于c++ - 为什么friend类可以通过Derived类访问到Base类私有(private)数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26288056/

相关文章:

c++ - 如何正确地将std::vector <std::vector <double>>强制转换为void *并重新解释回去?

c++ - 向客户端隐藏库内部类 C++ : use friend?

java - Java中类C++的友元类机制

C++ 重载运算符同时作为成员和函数?

c++ - 重置对象

C++ 无法在我的 Windows 应用程序中重写共享内存。它分配新的内存

c++ - 从 friend 类调用析构函数

C++特殊方法可见性

c++ - delete[] 是否等于每个元素删除。 C++

c++ - 具有派生模板类和继承成员变量的语法难题