第三次C++作业

友元类

一,引入友元类的目的

为了在其他类中访问一个类的私有成员在定义类的时候使用关键词friend定义友元函数或是友元类。

二,友元类的实现

1.友元函数

实现方式:friend 函数声明;

(1).普通函数对类的局限性

类的私有成员只能被类的成员访问,如果需要函数需要访问多个类,类的成员函数便很难实现。

例如计算建立一个point类表示一个点如果想计算两个点的距离,如果使用成员函数难以有效的表明二者的关系,需要一个函数联系两个不同的类时,一般函数难以满足需求。

(2).友元函数的实现

#include <iostream>
#include <math.h>
using namespace std;

class point
{
public:
    void set();
    void showdata();
    friend int distance(point &a,point &b);
private:
    int x;
    int y;
};

int distance(point &a,point &b)
{
    int way;
    way=sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
    return way;
}

void point::showdata()
{
    cout<<"x="<<x<<endl;
    cout<<"y="<<y<<endl;
}

void point::set()
{
    cout<<"输入x的值"<<endl;
    cin>>x;
    cout<<"输入Y的值"<<endl;
    cin>>y;
}

int main()
{
    point use_1,use_2;
    use_1.set();
    use_2.set();
    use_1.showdata();
    use_2.showdata();
    cout<<"两点之间的距离为"<<distance(use_1,use_2)<<endl;
}

在调试过程中只要输入两点的x,y值就能计算出两点之间的距离,函数distance()能够访问到point类中的私有数据,因为在定义point是distance在其中被定义为了友元类函数。

2.友元类

实现方式:friend 类申明;

(1).友元类的实现

#include <iostream>
using namespace std;

class birth
{
public:
    void set();
    friend class people; 
private:
    int year;
    int mon;
    int day;
};

class people
{
public:
    void set();
    void show(birth &a);
    friend class birth;
private:
    char name;

};

void people::show(birth &a)
{
    cout<<name<<endl;
    cout<<a.year<<endl;
    cout<<a.mon<<endl;
    cout<<a.day<<endl;
}

void people::set()
{
    cin>>name;
}

void birth::set()
{
    cin>>year;
    cin>>mon;
    cin>>day;
}

int main()
{
    people a;
    birth b;
    a.set();
    b.set();
    a.show(b);
}

 

(2).友元类的单向性

#include <iostream>
using namespace std;

class birth
{
public:
    void set();
private:
    int year;
    int mon;
    int day;
};

class people
{
public:
    void set();
    void show(birth &a);
    friend class birth;
private:
    char name;

};

void people::show(birth &a)
{
    cout<<name<<endl;
    cout<<a.year<<endl;
    cout<<a.mon<<endl;
    cout<<a.day<<endl;
}

void people::set()
{
    cin>>name;
}

void birth::set()
{
    cin>>year;
    cin>>mon;
    cin>>day;
}

int main()
{
    people a;
    birth b;
    a.set();
    b.set();
    a.show(b);
}

如例所示,将birth类中的friend class people 该函数便不能正常运行。要想实现相互访问只能在两个类中同时定义友元类。

(3).友元类的不可传递性

不同与a=b,b=c,a=c;如果A是B的友元类,B是C的友元类那么A不是C的友元类。

三,实验设计

利用友元类完成一个员工资料统计系统,能够打印出员工的个人信息与公司信息,其中个人信息是公司信息的友元类。要求这两个类的私有成员在一个函数中赋值,并使用友元函数打印信息。

posted on 2019-09-29 10:16  zero-one  阅读(206)  评论(0编辑  收藏  举报

导航