C++——2-14友元

#ifndef BOY_H
#define BOY_H

#include <iostream>
#include <string>
#include "Girl.h"

using namespace std;

class Boy
{
public:
    Boy(){}
    Boy(string name, string phone, string face);

    string m_strFace;
    //若將一個類申明為友元,
    //則在該類所有函數中都可以訪問Boy的私有數據
    friend class Girl;
    //若將一個類中的某個成員函數申明為友元
    //則只能在該函數中訪問Boy的私有數據
    //friend void Girl::getBoyName(Boy &boy);

    //友元函數
    //在友元函數可以通過對象直接訪問和操作該對象的私有數據
    //友元破壞了類的封裝性,盡量不要用
    friend void fun(Boy &boy);

private:
    string m_strName;
    string m_strPhone;
};
void fun(Boy &boy);

#endif
#ifndef GIRL_H
#define GIRL_H

#include <iostream>
#include <string>


using namespace std;

class Boy;

class Girl
{
public:
    void getBoyName(Boy &boy);
    void getBoyPhone(Boy &boy);
};

#endif
#include "Girl.h"
#include "boy.h"

void Girl::getBoyName(Boy &boy)
{
    cout << boy.m_strName << endl;
}
void Girl::getBoyPhone(Boy &boy)
{
    cout << boy.m_strPhone << endl;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容