这是我第一次在这里发帖。
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/