这是我第一次在这里发帖提问.
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.
}
};
Run Code Online (Sandbox Code Playgroud)
问题在课程问题的最后一行中指出.
friend适用于该类型的所有成员,无论该类型是否是继承的。强调这一点:共享的是成员。
这意味着您的Question类可以访问 的所有成员Base,即int Base::base. 是否通过 的实例访问该成员Derived是无关紧要的,因为被访问的实际成员是在 上声明的Base。