这是我第一次在这里发帖提问。
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.
}
};
问题显示在课程问题的最后一行。
答案 0 :(得分:2)
friend
适用于该类型的所有成员,无论该类型是否被继承。要强调这一点:共享成员。
这意味着您的Question
班级可以访问Base
的所有成员,这只是int Base::base
。它是否通过Derived
实例访问此成员是无关紧要的,因为正在访问的实际成员是在Base
上声明的。