了解成员访问与C++中的继承/友元类
Understanding member access with inheritance / friend class in C++
摘自C++入门第5版:
看看这些类:
class Base {
friend class Pal;
public:
void pub_mem();
protected:
int prot_mem;
private:
int priv_mem;
};
class Sneaky : public Base {
private:
int j;
};
class Pal {
public:
int f1(Base b){
return b.prot_mem; //OK, Pal is friend class
}
int f2(Sneaky s){
return s.j; //error: Pal not friend, j is private
}
int f3(Sneaky s){
return s.prot_mem; //ok Pal is friend
}
}
这里 Pal 是 Base 的好友类,而 Sneaky 继承自 Base 并在 Pal 中使用。现在调用s.prot_mem
的最后一行,作者给出了它工作的原因,因为 Pal 是 Base 的好友类。但是到目前为止我读到的,我的理解告诉我它应该随时工作,因为 s 派生自 Base,prot_mem是 Base 类的受保护成员,应该已经可以访问 Sneaky,你能解释为什么我错了或更多详细说明吗?
我的理解告诉我,无论如何它都应该有效,因为 派生自基,prot_mem是基类的受保护成员, 应该已经可以访问鬼鬼祟祟
不可以,受保护的变量prot_mem
只能由派生类成员访问,而不能由第三方类成员访问,如class Pal
,如果Pal
不是Base
的朋友。
没有友谊,Pal
只能看到Sneaky或Base的公众成员。Base
的一个成员受到保护这一事实对Pal
没有任何好处——它只会使Sneaky
受益。
问题是,虽然Sneaky
可以访问prot_mem
,但您显示的代码不是Sneaky
,而是Pal
。如果Pal
是一个不相关的类,它就无法访问prot_mem
,这也在Sneaky
中受到保护。但是,Pal
是Base
的朋友,这使它具有必要的访问权限。
相关文章:
- C++模板来检查友元函数的存在
- 模板类无法识别友元运算符
- 如何使用单独文件中的派生类访问友元函数对象
- 模板化的类和友元函数
- 为什么创建友元类的实例会导致"undefined reference to"错误?
- 如何在嵌套类中正确使用友元声明?
- 继承和友元函数,从基类访问受保护的成员
- 为什么友元函数无法访问继承类的私有变量?
- 什么时候使用友元类/函数而不是继承
- 具有继承的友元类
- 为什么 Visual C++无法编译从私有嵌套类继承的友元模板
- 友元类和继承
- 友元结构继承类时不可访问
- 继承:重用友元类中的运算符重载
- 如何使用具有继承和模板的友元类
- 了解成员访问与C++中的继承/友元类
- 使用模板参数友元从类继承
- c++友元继承
- 它的友元函数在这里被继承
- 模板类层次友元继承