我想使用对方的私有乘员函数,必须对方声明我是它的朋友才行。
然后我把对方作为我的函数参数使用。
一个管理类对象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;
}