我们知道一个类无法访问其他类的私有成员。类似地,不继承另一个类的类不能访问其受保护的成员。
友元类:
友元类是一个类,可以访问被声明为友元的类的私有成员和受保护成员。当我们想要允许特定类访问类的私有成员和受保护成员时,这是必需的。
函数类示例
在这个例子中,我们有两个类XYZ和ABC。 XYZ类有两个私有数据成员ch和num,这个类将ABC声明为友元类。这意味着ABC可以访问XYZ的私有成员,在ABC类的函数disp()访问私有成员num和ch的示例中也证明了这一点。在这个例子中,我们将对象作为参数传递给函数。
#include <iostream>using namespace std;class XYZ {private: char ch='A'; int num = 11;public: /* This statement would make class ABC * a friend class of XYZ, this means that * ABC can access the private and protected * members of XYZ class. */ friend class ABC;};class ABC {public: void disp(XYZ obj){ cout<<obj.ch<<endl; cout<<obj.num<<endl; }};int main() { ABC obj; XYZ obj2; obj.disp(obj2); return 0;}输出:
A11
友元函数:
与友元类相似,此函数可以访问另一个类的私有和受保护成员。全局函数也可以声明为友元,如下例所示:
友元函数示例
#include <iostream>using namespace std;class XYZ {private: int num=100; char ch='Z';public: friend void disp(XYZ obj);};//Global Functionvoid disp(XYZ obj){ cout<<obj.num<<endl; cout<<obj.ch<<endl;}int main() { XYZ obj; disp(obj); return 0;}输出:
100Z
