我想要一个对象HIDDevice
,它维护自己的静态std::map
。然而,当构造函数和析构函数被设置为私有时,下面的类会导致编译错误,如下所示:
class HIDDevice
{
public:
static HIDDevice* getDevice(unsigned short vendorID, unsigned short productID);
int writeData(const unsigned char *data, int length);
int readData(unsigned char *data, int length);
private:
static std::map<std::string, HIDDevice> m_hidDevices;
static bool isInitialized;
static void initHIDAPI();
HIDDevice(){};
HIDDevice(unsigned short vendorID, unsigned short productID, std::string serialNumber = "");
HIDDevice(std::string path);
~HIDDevice();
};
编辑
错误消息如下:
error C2248: 'HIDDevice::HIDDevice' : cannot access private member declared in class 'HIDDevice'
std::map
不会因为碰巧有一个类型为std::map<something>
的静态成员而获得对类的私有成员的特殊访问权限。
不能仅将std::map
声明为友元,因为不能保证构造函数和析构函数实际上是由std::map
的成员调用的。这个任务很可能被委托给内部实现类或独立函数。
即使你设法交到了必要的朋友,这对你也没有多大好处,因为任何人都可以声明相同类型的std::map
,并在自己的映射中创建你类的对象。
我建议只公开构造函数和析构函数。