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
}
};
Reference: "The C++ Programming Language" Bjarne Stroustrup
More explanation (mine): If 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
.
Now, if friendship could be inherited, then someone just needs to inherit 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…