首页 > 编程知识 正文

友元函数有this指针吗,友元函数可以访问protected

时间:2023-05-05 07:08:03 阅读:261815 作者:3875

C++中引入友元函数的目的是让函数或类能够访问一个类的私有数据。


友元函数不是当前类的成员函数,需要在其函数名前加上关键字friend,友元函数需要声明在当前类中,而定义可以在类中,也可以在类外。


我们知道一个类中的成员函数也是可以访问当前类中的所有私有数据,那么为什么不把友元函数写成类自己的成员函数呢?那么我们来举一个简单的例子。


比如函数void Print(const Girl *a,const Boy *b); 如果把它定义在Girl类里则无法访问Boy类里面的私有数据,如果把它定义在Boy类里,则无法访问Girl类里面的私有数据。也就是说没有friend类型就无法使用这个函数。


有了friend,我们可以把void Print(const Girl *a,const Boy *b);声明为全局函数,然后再在每个类中把它作为friend类型就可以了。


例子:

#include <iostream>#include <string.h>#include <stdio.h>using namespace std;class Boy; //向前引用class Girl{ private: int age; char name[25]; public: Girl(int age,char name[]) { this->age = age; strcpy(this->name,name); } friend void Print(const Girl *a,const Boy *b);};class Boy{ private: int age; char name[25]; public: Boy(int age,char name[]) { this->age = age; strcpy(this->name,name); } friend void Print(const Girl *a,const Boy *b);};void Print(const Girl *a,const Boy *b){ cout<<a->name<<" "<<a->age<<endl; cout<<b->name<<" "<<b->age<<endl;}int main(){ Girl *a = new Girl(18,"Lisa"); Boy *b = new Boy(20,"Jimi"); Print(a,b); return 0;}


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。