我有以下查询;继承和友谊访问。 C++
classB inherits from classA
classC is friend of classB
这是否意味着classC应该能够访问classA的protected成员?由于classB从classA继承了此类,因此classC可以访问类classB中的所有内容?
我有以下查询;继承和友谊访问。 C++
classB inherits from classA
classC is friend of classB
这是否意味着classC应该能够访问classA的protected成员?由于classB从classA继承了此类,因此classC可以访问类classB中的所有内容?
这意味着classC
应该能够访问的classB
保护classA
子对象的一部分。应该不能够从classA
本身访问任何非公开的。
例如:
class C;
class A
{
protected:
int i;
};
class B:
public A
{
friend class C;
};
class C
{
public:
void foo(A& a, B& b)
{
// a.i = 3; // not allowed
b.i = 3; // allowed, accesses the `i` of the `A` subobject of `B`
}
};
[我原来的答复是无稽之谈。为此道歉。谢谢@celtschk指出了这一点,并提供更好的答案。]
如果C
是B
的朋友,它可以访问所有B
的成员,私人,市民是否,或受保护的,而且包括访问(public和protected)成员是基类子对象的一部分:
struct A { protected: int a; };
struct B : A { private: int b; friend struct C; }
struct C
{
B x;
A w;
void f()
{
x.a = 1; // fine
x.b = 2; // fine
// w.a = 0; /* Error, #1 */
}
friend struct D; // see below
};
但是,友谊既不是传递还是继承:C
是B
的朋友,但不是A
(见#1)。另外,如果D
是C
的好友,那么D
不会获得任何C
的友谊给B
所提供的访问权限,因此D
不能访问B
的非公共成员。同样,如果从C
struct E : C
继承,然后E
也没有的B
朋友自动:
struct D
{
B y;
void g()
{
// y.b = 3; /* Error! */
}
};
struct E : C
{
B z;
void h()
{
// y.b = 4; /* Error! */
}
}
或许可以总结一下的事情在几个点:
派生类访问给每个基类的所有公共和受保护的成员。
一个类的一个朋友有权访问对访问它(即不包括专用基站成员的所有成员)该类别的所有成员。
友谊是不能继承:如果一个类有一个朋友,友谊并不适用于任何其基类的也没有任何派生类的。
一个朋友的朋友是不是朋友。
这是原始问题的更好答案。 – 2012-04-05 21:08:14
@KerrekSB:谢谢。 – celtschk 2012-04-05 21:15:25