入门教程:实例详解C 友元2

来源:百度文库 编辑:神马文学网 时间:2024/06/30 19:34:15
一个普通函数可以是多个类的友元函数,对上面的代码我们进行修改,注意观察变化:#include 
using namespace std;
class Country;
class Internet
{
public:
Internet(char *name,char *address)
{
strcpy(Internet::name,name);
strcpy(Internet::address,address);
}
friend void ShowN(Internet &obj,Country &cn);//注意这里
public:
char name[20];
char address[20];
};
class Country
{
public:
Country()
{
strcpy(cname,"中国");
}
friend void ShowN(Internet &obj,Country &cn);//注意这里
protected:
char cname[30];
};
void ShowN(Internet &obj,Country &cn)
{
cout<}
void main()
{
Internet a("中国软件开发实验室","www.cndev-lab.com");
Country b;
ShowN(a,b);
cin.get();
}
一个类的成员函数函数也可以是另一个类的友元,从而可以使得一个类的成员函数可以操作另一个类的数据成员,我们在下面的代码中增加一类Country,注意观察:
#include 
using namespace std;
class Internet;
class Country
{
public:
Country()
{
strcpy(cname,"中国");
}
void Editurl(Internet &temp);//成员函数的声明
protected:
char cname[30];
};
class Internet
{
public:
Internet(char *name,char *address)
{
strcpy(Internet::name,name);
strcpy(Internet::address,address);
}
friend void Country::Editurl(Internet &temp);//友元函数的声明
protected:
char name[20];
char address[20];
};
void Country::Editurl(Internet &temp)//成员函数的外部定义
{
strcpy(temp.address,"edu.cndev-lab.com");
cout<}
void main()
{
Internet a("中国软件开发实验室","www.cndev-lab.com");
Country b;
b.Editurl(a);
cin.get();
}
整个类也可以是另一个类的友元,该友元也可以称做为友类。友类的每个成员函数都可以访问另一个类的所有成员。