類的友元
一、友元函數(shù)
一個類的友元函數(shù)是定義在類外部的一個函數(shù),它不是類的成員函數(shù),但可以訪問類的私有成員和公有成員。
定義格式如下:
friend?? 返回值類型 友元函數(shù)名<參數(shù)表>
例:
#include<iostream.h>
class add
{
private:
?int a,b,c;
public:
?void inst(int x,int y);
?friend int sum(add &m);
};
void add::inst(int x, int y)
{
?a=x;
?b=y;
}
int sum(add &m)
{
?m.c=m.a+m.b;
?return m.c;
}
void main()
{
?add t;
?t.inst(20,30);
?cout<<"sum="<<sum(t)<<endl;
}
二、友元類
一個函數(shù)可以作為一個類的友元,一個類也可以作為另一個類的友元,這種類稱為友元類。
例:
#include<iostream.h>
class A
{
private:
?int x,y;
?friend class B;
public:
?void inst(int a,int b)
?{
??x=a;
??y=b;
?}
?void show();
};
void A::show()
{
?cout<<"x="<<x<<endl;
?cout<<"y="<<y<<endl;
}
class B
{
private:
?int z;
?A m;
public:
?void add(int a,int b);
};
void B::add(int a,int b)
{
?m.x=a;
?m.y=b;
?z=m.x+m.y;
?cout<<"z="<<z<<endl;
}
void main()
{
?A m;
?B t;
?m.inst(3,8);
?m.show();
?t.add(30,19);
}
友元成員
一個類的成員函數(shù)可以作為另一個類的友元,這種成員函數(shù)稱為友元函數(shù)成員。
友元成員函數(shù)不僅可以訪問自己所在類中的私有成員,還可以訪問friend聲明所在類中的私有成員。
#include<iostream.h>
class B;
class A
{
private:
?int x;
?int y;
public:
?void inst(int a,int b)
?{
??x=a;
??y=b;
?}
?void show(B &);
};
class B
{
private:
?int z;
public:
?friend void A::show(B &);
};
void A::show(B &m)
{
?m.z=x+y;
?cout<<"x="<<x<<endl;
?cout<<"y="<<y<<endl;
?cout<<"m.z="<<m.z<<endl;
}
void main()
{
?A m;
?B t;
?m.inst(12,18);
?m.show(t);
}