友元函数

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;
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值