C++中的友元机制(friend),可以不通过调用成员函数便能直接访问类的私有数据。友元可以是函数(友元函数),也可以是类(友元类)。
一、友元函数
1.声明:在类体内,在函数类型前要加关键字friend;
2.定义:在类体外,格式与普通函数一样;
3.特点:(1)友元函数为非成员函数,调用上与普通函数一样;
(2)可直接访问该类中私有成员。
二、友元类
当声明一个类为另一个类的友元时,友元类中的所有成员函数都是另一个类的友元函数。
通过下面的代码例子,就会更明白了。
-
#include
<iostream>
-
using namespace std;
-
-
class X
-
{
-
public:
-
friend class Y; //类Y是类X的友元类
-
void set(int i)
-
{
-
x = i;
-
}
-
void display()
-
{
-
cout
<< "x=" << x << ";" << "y:" << y <<endl;
-
}
-
private:
-
int x;
-
static int y;
-
};
-
-
class Y
-
{
-
public:
-
Y(int i,int j);
-
void display();
-
private:
-
X a; //数据成员为类X的对象
-
};
-
-
int X::y = 10;
-
Y::Y(int i,int j)
-
{
-
a.x = i;
-
X::y = j;
-
}
-
-
void Y::display()
-
{
-
cout << "x=" << a.x << "," << "y=" << X::y <<endl;
-
}
-
-
int main()
-
{
-
X b;
-
b.set(5);
-
b.display();
-
Y c(6,9);
-
c.display();
-
b.display();
-
-
return 0;
-
}
-
-
运行结果为:
注意:友元机制的作用主要是为了提高程序的运行效率和方便编程。但同时友元破坏了类的封装性,所以使用时慎重。
<div class="person-messagebox">
<div class="left-message"><a href="https://blog.csdn.net/buknow">
<img src="https://profile.csdnimg.cn/D/E/4/3_buknow" class="avatar_pic" username="buknow">
</a></div>
<div class="middle-message">
<div class="title"><span class="tit "><a href="https://blog.csdn.net/buknow" data-report-click="{"mod":"popu_379","ab":"new"}" target="_blank">n大橘为重n</a></span>
<!-- 等级,level -->
<img class="identity-icon" src="https://csdnimg.cn/identity/blog5.png"> </div>
<div class="text"><span>原创文章 89</span><span>获赞 224</span><span>访问量 15万+</span></div>
</div>
<div class="right-message">
<a class="btn btn-sm bt-button personal-watch" data-report-click="{"mod":"popu_379","ab":"new"}">关注</a>
<a href="https://im.csdn.net/im/main.html?userName=buknow" target="_blank" class="btn btn-sm bt-button personal-letter">私信
</a>
</div>
</div>
</div>