C++友元函数

C++友元函数

  • 尽管友元函数的原型有在类的定义中出现过,但是友元函数并不是成员函数。
  • 类的友元函数是定义在类外部,但有权访问类的所有私有(private)成员和保护(protected)成员。

友元可以是一个函数,该函数被称为友元函数;友元也可以是一个类,该类被称为友元类,在这种情况下,整个类及其所有成员都是友元。

如果要声明函数为一个类的友元,需要在类定义中该函数原型前使用关键字 friend

1
2
3
4
5
6
7
8
class Box
{
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};

声明类 ClassTwo 的所有成员函数作为类 ClassOne 的友元,需要在类 ClassOne 的定义中放置如下声明:

1
friend class ClassTwo;

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<bits\stdc++.h>
using namespace std;
class Box
{
double width;
public:
friend void printWidth(Box box);
void setWidth(double wid);
};
void Box::setWidth(double wid)
{
width = wid;
}
void printWidth(Box box)
{
cout <<"Width of box : "<<box.width<<endl;
}

int main()
{
Box box;
box.setWidth(10.0);
printWidth(box);


system("pause");
return 0;
}

运行结果:

1
Width of box : 10

C++友元函数
http://example.com/2022/10/12/C-友元函数/
作者
north
发布于
2022年10月12日
许可协议