分类: C/C++
2007-09-12 03:02:30
在C++中,struct关键字和class关键字功能基本一致,除了struct的默认控制为public而class为private之外。友员指的是可以对某个struct或者class的内部私有数据进行访问的对象、全局函数或者某种类型对象的内部函数。下面是友员机制的例子:
struct X; //预先声明结构X
struct Y{
void f(X *);
};
struct X{ //此处对结构X进行定义
private:
int i;
public:
void initialize();
friend void g(X*,int);
friend void Y::f(X*);
friend struct Z;
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);
}
同时友员也支持struct或者class的嵌套。
#include
#include
#define SZ 20
//This is an example for friend of embeded.
//here,keyword class may be replaced by struct
class holder{
private:
int a[SZ];
public:
void initialize();
friend struct pointer;
class pointer{
private:
holder * h;
int * p;
public:
void initialize(holder * H);
void next();
void previous();
void top();
void end();
int read();
void set(int i);
};
//friend holder::pointer; //this format is wrong
//friend struct pointer; //also could be moved here
};
void holder::initialize()
{
memset(a,0,SZ*sizeof(int));
}
void holder::pointer::initialize(holder * H)
{
h=H;
p=h->a;
}
void holder::pointer::next(){
if (p<&(h->a[SZ-1]))p++;
}
void holder::pointer::previous()
{
if (p>&(h->a[0])) p--;
}
void holder::pointer::top()
{
p=&(h->a[0]);
}
void holder::pointer::end()
{
p=&(h->a[SZ-1]);
}
int holder::pointer::read()
{
return *p;
}
void holder::pointer::set(int i)
{
*p=i;
}
main()
{
holder h;
holder::pointer hp,hp2;
int i;
h.initialize();
hp.initialize(&h);
hp2.initialize(&h);
for (i=0;i
{
hp.set(i);
hp.next();
}
hp.top();
hp2.end();
for(i=0;i
{
printf("hp=%d,hp2=%d\n",hp.read(),hp2.read());
hp.next();
hp2.previous();
}
}