友元解决了那些问题

我想使用对方的私有乘员函数,必须对方声明我是它的朋友才行。  
然后我把对方作为我的函数参数使用。
一个管理类对象DeviceMgr包含被管理对象Device,DeviceMgr可能频繁使用到Device的私有乘员。
这样可以在Device里面声明说,“DeviceMgr是我的朋友类”,这样就可以在DeviceMgr里面方便的使用Device的私有成员了。
当然,为了简洁,请不要考虑Device的封装性问题。

#include <iostream>
#include <map>
using namespace std;
class DeviceMgr;
class  Device
{
//private:
	friend class DeviceMgr;
public:
	std::string  m_DeviceName;
	Device(std::string deviceName):m_DeviceName(deviceName){;}
};
class DeviceMgr
{
private:
	std::map<int,Device*>m_deviceMap;
public:
	void AddDevice(Device*p)
	{
        m_deviceMap[m_deviceMap.size()] = p;
	}
	void DisplayDevice()
	{
		std::map<int,Device*>::iterator it = m_deviceMap.begin();
        for (;it!=m_deviceMap.end();it++)
        {
		    //本来Device的私有乘员变量在这里不能用的
			std::cout<<it->second->m_DeviceName.c_str()<<std::endl;
        }
	}
};

int main()
{
    Device A("PCI");
    Device B("NET");
    DeviceMgr mgr;
    mgr.AddDevice(&A);
    mgr.AddDevice(&B);
    mgr.DisplayDevice();
    return 0;
}
       


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值