友元类继承 [英] friend class with inheritance
问题描述
如果我有两个继承类如下:
class A
{
.. 。
}
class B:public A
{
...
}
第三个类定义为A类朋友:
class C
{
friend class A;
}
我是否可以从 / code>(其也是
A
类型的对象)类C
的所有成员,已经定义 class B
首先是朋友Class?
friend
ship既不是继承也不是可传递的。它是两个类之间严格一对一的关系。
A类{
朋友class B;
int Aries;
};
class B {
friend class C;
int Taurus;
};
class C {
int Leo;
void Capricorn(){
A a;
a.Aries = 0; // this wont work,C is not a friend of A.
//友谊不是传递的
}
};
class D:public C {
void Gemini(){
B b;
b.Taurus = 0; // this wont work,D不是B的朋友。
//友谊不是继承的
}
};
class E:public B {
void Scorpio(){
C c;
c.Leo = 0; // this wont work either,friendship is not inherited
}
};
参考:C ++编程语言Bjarne Stroustrup
更多解释(我的):如果 现在,如果友谊可以继承,那么有人只需要继承 If I have two Classes as follows with inheritance: And a third class with defined as a friend class A: Will I be able to access from Reference: "The C++ Programming Language" Bjarne Stroustrup More explanation (mine): If Now, if friendship could be inherited, then someone just needs to inherit 这篇关于友元类继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! friend
船不是一对一,它将是封装的结束。请注意, B
类只能访问 A
的成员 private
如果 A
的类声明将 B
声明为 friend
。 B 不能强制
朋友
在 A
>
B
即可访问 A
,没有 A
在阻止它。此外,允许 friend
是可传递的会导致其他问题,因为现在 B
可能有 friend
C
,他们可以有朋友
D
,一直到 Z
。所有 B
, C
, D
,... , Z
现在可以访问 A
的私人
这将是一场灾难。 class A
{
...
}
class B : public A
{
...
}
class C
{
friend class A;
}
class B
(which is also an object of type A
) all members of class C
as if I had defined class B
the friend Class in the first place?friend
ship is neither inherited nor transitive. It is strictly one-one relationship between two classes. class A {
friend class B;
int Aries;
};
class B {
friend class C;
int Taurus;
};
class C {
int Leo;
void Capricorn() {
A a;
a.Aries = 0; // this wont work, C is not a friend of A.
// friendship is not transitive
}
};
class D : public C {
void Gemini() {
B b;
b.Taurus = 0; // this wont work, D is not a friend of B.
// friendship is not inherited
}
};
class E : public B {
void Scorpio() {
C c;
c.Leo = 0; // this wont work either, friendship is not inherited
}
};
friend
ship were not one-one, it would be the end of encapsulation. Note that B
class can access private
members of A
only if the class declaration of A
declares B
as friend
. B
cannot enforce friend
ship on A
.B
to access private members of A
, without A
having any say in preventing it. Also, allowing friend
ship to be transitive would lead to other problems, since now B
could have a friend
C
, who in turn could have a friend
D
, all the way to Z
. All of B
, C
, D
, ..., Z
can now access A
's private
members, which would be a disaster.