友元(允许不属于该结构的成员存取结构中的数据)
在原文的代码中用关键词friend声明了外部函数,外部结构,外部结构中的函数作为X的友元,允许其存取X中的private变量。
值得注意的是,原结构A的嵌套结构B中的函数无法调用上层结构A中的private变量,也须声明B的函数为A的友元方能调用B的private变量,称为嵌套友元。
//:FRIEND.CPP--Friend allows special access
struct X;
struct Y{
void f(X*);
};
struct X{
private:
int i;
public:
void initialize();
friend void g(X*,int);//global friend
friend void Y::f(X*);//struct member friend
friend struct Z;//Entire struct is a friend
friend void h();
};
void X::initialize(){
i=0;
}
void g(X* x,int i){
x->i=i;
}
void Y::f(X* x){
x->i=47;
}
struct Z{
private:
int j;
public:
void initialize();
void g(X* x);
};
void Z::initialize(){
j=99;
}
void Z::g(X* x){
x->i+=j;
}
void h(){
X x;
x.i=100;
}
main(){
X x;
Z z;
z.g(&x);
}