具有私有构造函数和自身静态容器(映射)的对象
Object with private constructor and a static container (map) of itself?
我想要一个对象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
,并在自己的映射中创建你类的对象。
我建议只公开构造函数和析构函数。
相关文章:
- 使用std::函数映射对象方法
- 使用"std::unordereded_map"映射到"std::list"对象
- 在c++中访问int到类对象的映射时出错
- 如何创建对象函数指针C++映射?
- 准确了解对象在内存中的映射方式
- 将包含不可复制对象的对插入到映射中
- 用unordered_map映射对象作为键
- 如何通过文件映射对象重新映射共享内存的视图?
- 文件映射对象和文件对象可以互换使用吗
- 如何从 std::映射'm'对象中返回 Iter 以'n'选定对象 (c++)
- 包含抽象基类ptr_map的映射对象
- C++ 映射对象的顺序
- 更新标准::映射对象数据
- C++ 内存泄漏与我的 std::映射 &对象和标准::矢量 &对象
- Windows CreateFileMapping:具有相同支持文件的不同文件映射对象
- 使用C++中的文件映射对象进行读取
- c++构造函数映射对象(已编辑)
- 在映射对象上定义自定义迭代器:神秘的"incomplete type"错误
- 在(c++) cocos2dx中添加映射对象到Vector
- c++代码中共享文件映射对象大小的问题