如果将函数定义为C++中的友元函数,则可以使用该函数访问类的受保护数据和私有数据。
通过使用关键字Friend Compiler可以知道给定的函数是一个Friend函数。
为了访问数据,应该在类的主体内(从关键字friend开始)声明friend函数。
class class_name { friend data_type function_name(argument/s); //friend 函数. };
在上面的声明中,friend函数的前面是关键字friend。可以像常规C++函数一样在程序中的任何位置定义函数。函数定义不使用关键字 friend或范围解析运算符。
friend函数特征:
让我们看一下用于打印盒子长度的C++友元函数的简单示例。
#include <iostream> using namespace std; class Box { private: int length; public: Box(): length(0) { } friend int printLength(Box); //friend函数 }; int printLength(Box b) { b.length += 10; return b.length; } int main() { Box b; cout<<"Length of box: "<< printLength(b)<<endl; return 0; }
输出:
Length of box: 10
让我们看一个简单的示例
#include <iostream> using namespace std; class B; //forward 声明. class A { int x; public: void setdata(int i) { x=i; } friend void min(A,B); //friend 函数. }; class B { int y; public: void setdata(int i) { y=i; } friend void min(A,B); //friend 函数 }; void min(A a,B b) { if(a.x<=b.y) std::cout << a.x << std::endl; else std::cout << b.y << std::endl; } int main() { A a; B b; a.setdata(10); b.setdata(20); min(a,b); return 0; }
输出:
10
在上面的示例中,min()函数对两个类友好,即min()函数可以访问类A和B的私有成员。
友元类可以访问已声明为友元的类的私有成员和受保护成员。
#include <iostream> using namespace std; class A { int x =5; friend class B; //friend类. }; class B { public: void display(A &a) { cout<<"value of x is : "<<a.x; } }; int main() { A a; B b; b.display(a); return 0; }
输出:
value of x is : 5
在上面的示例中,类B被声明为类A内的友元。因此,类B是类A的友元。类B可以访问类A的私有成员。
链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-friend-function.html
来源:LearnFk无涯教程网
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)