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

来源:百度文库 编辑:神马文学网 时间:2024/04/29 14:35:00
示例代码如下:
 
#include 
using namespace std;
class Internet;
class Country
{
public:
Country()
{
strcpy(cname,"中国");
}
friend class Internet;//友类的声明
protected:
char cname[30];
};
class Internet
{
public:
Internet(char *name,char *address)
{
strcpy(Internet::name,name);
strcpy(Internet::address,address);
}
void Editcname(Country &temp);
protected:
char name[20];
char address[20];
};
void Internet::Editcname(Country &temp)
{
strcpy(temp.cname,"中华人民共和国");
}
void main()
{
Internet a("中国软件开发实验室","www.cndev-lab.com");
Country b;
a.Editcname(b);
cin.get();
}
在上面的代码中我们成功的通过Internet类Editcname成员函数操作了Country类的保护成员cname。
在编程中,我们使用友元的另外一个重要原因是为了方便重载操作符的使用,这些内容我们将在后面的教程着重讨论!