C++技术交流

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  6 随笔 :: 8 文章 :: 1 评论 :: 0 Trackbacks

类的友元

一、友元函数
一个类的友元函数是定义在类外部的一个函数,它不是类的成员函数,但可以访问类的私有成员和公有成员。

定义格式如下:
friend   返回值类型 友元函数名<参数表>

例:
#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;
}


二、友元类

一个函数可以作为一个类的友元,一个类也可以作为另一个类的友元,这种类称为友元类。

例:

#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);
}


友元成员


一个类的成员函数可以作为另一个类的友元,这种成员函数称为友元函数成员。
友元成员函数不仅可以访问自己所在类中的私有成员,还可以访问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);
}

posted on 2006-06-23 23:18 啊嵩 阅读(101) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理