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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容