您的位置:首页 > 编程语言 > C语言/C++

c++中友元机制

2015-05-30 20:08 344 查看
友元的概念:遵循一定规则而使对象以外的软件系统能够不经过消息传递方式而直接访问对象内封装的数据成员的技术方法便是友元。

只要将外界的某个对象说明为一个类的友元,那么这个外界对象就可以访问这个类对象中的私有成员。

声明为友元的外界对象既可以是另一个类的成员函数,也可以是不属于任何类的一般函数,还可以是整个类(这样,此类中的所有成员函数都成为友元函数)。

1.友元函数

先来一段代码,让大家看看友元函数的用法吧!

#define strmax 32
#include<iostream>
#include<string>
using namespace std;
class myclass
{
int x,y;
char *string;
public:
myclass(int vx,int vy,char *str){
x=vx;
y=vy;
string=new char[strmax];
strcpy(string,str);
}
//friend int sum(myclass c1);
};
int sum(myclass c1)
{
return c1.x+c1.y;
}
int main()
{
myclass c1(10,10,"my myclass object!");
cout<<"the sum is:"<<sum(c1)<<endl;

return 0;

}


编译结果如下:

Compiling...
friend1.cpp
F:\c++\friend1.cpp(20) : error C2248: 'x' : cannot access private member declared in class 'myclass'
F:\c++\friend1.cpp(7) : see declaration of 'x'
F:\c++\friend1.cpp(20) : error C2248: 'y' : cannot access private member declared in class 'myclass'
F:\c++\friend1.cpp(7) : see declaration of 'y'
Error executing cl.exe.

friend1.exe - 2 error(s), 0 warning(s)

由于对象访问了private成员变量,因此编译会失败!

现在去掉注释,代码如下:

#define strmax 32
#include<iostream>
#include<string>
using namespace std;
class myclass
{
int x,y;
char *string;
public:
myclass(int vx,int vy,char *str){
x=vx;
y=vy;
string=new char[strmax];
strcpy(string,str);
}
friend int sum(myclass c1);
};
int sum(myclass c1)
{
return c1.x+c1.y;
}
int main()
{
myclass c1(10,10,"my myclass object!");
cout<<"the sum is:"<<sum(c1)<<endl;

return 0;

}


编译通过,而且结果为the sum is:20

2.友元成员

另一个类的成员函数作为某个类的友元,只是在声明友元函数时要加上成员函数所在的类名,称为友元函数。

3.友元类

某个类可以是另一个类的友元,这样作为友元的类中的所有成员函数都可以访问声明其为友元类的类中的全部成员。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: