什么时候在 C++ 中使用 'friend'?
类的友元函数在该类的作用域之外定义,但它有权访问该类的所有私有和受保护的成员。即使友元函数的原型出现在类定义中,友元也不是成员函数。
友元可以是函数、函数模板或成员函数,也可以是类或类模板,在这种情况下,整个类及其所有成员都是友元。
要将函数声明为类的友元,请在类定义中使用关键字 friend 来表示函数原型,如下所示 -
class Box {
double width;
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};要将 ClassTwo 类的所有成员函数声明为 ClassOne 类的友元,请在 ClassOne 类的定义中放置以下声明
示例
friend class ClassTwo;
For example,
#include <iostream>
using namespace std;
class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
// Member function definition
void Box::setWidth( double wid ) {
width = wid;
}
// Note: printWidth() is not a member function of any class.
void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}
// Main function for the program
int main() {
Box box;
// set box width without member function
box.setWidth(10.0);
// Use friend function to print the wdith.
printWidth( box );
return 0;
}输出
这将产生如下输出 -
Width of box: 10
即使函数不是类的成员,它也可以直接访问该类的成员变量。这在某些情况下非常有用。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP