首页 > 其他 > 详细

友元函数

时间:2014-02-13 03:41:13      阅读:337      评论:0      收藏:0      [点我收藏+]

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



友元函数

原文:http://blog.csdn.net/acdreamers/article/details/19120563

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!