第三次C++做業

友元類

一,引入友元類的目的ios

爲了在其餘類中訪問一個類的私有成員在定義類的時候使用關鍵詞friend定義友元函數或是友元類。函數

二,友元類的實現spa

1.友元函數設計

實現方式:friend 函數聲明;

(1).普通函數對類的侷限性調試

類的私有成員只能被類的成員訪問,若是須要函數須要訪問多個類,類的成員函數便很難實現。code

例如計算創建一個point類表示一個點若是想計算兩個點的距離,若是使用成員函數難以有效的代表兩者的關係,須要一個函數聯繫兩個不一樣的類時,通常函數難以知足需求。blog

(2).友元函數的實現ci

#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在其中被定義爲了友元類函數。io

2.友元類class

實現方式: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的友元類。

三,實驗設計

利用友元類完成一個員工資料統計系統,可以打印出員工的我的信息與公司信息,其中我的信息是公司信息的友元類。要求這兩個類的私有成員在一個函數中賦值,並使用友元函數打印信息。

相關文章
相關標籤/搜索