Pointers 将std::map与指针一起使用
我尝试在类中使用std::map作为属性。我使用Visual Studio 2012,我的课程如下:Pointers 将std::map与指针一起使用,pointers,stl,c++-cli,clr,Pointers,Stl,C++ Cli,Clr,我尝试在类中使用std::map作为属性。我使用Visual Studio 2012,我的课程如下: public ref class MyClass { std::map<std::wstring,MyType> * mpMyMap; MyClass() { mpMyMap = new std::map<std::wstring,MyType>(); } ~MyClass() { delete mpMyMap; } Get(std::wstring na
public ref class MyClass
{
std::map<std::wstring,MyType> * mpMyMap;
MyClass()
{
mpMyMap = new std::map<std::wstring,MyType>();
}
~MyClass()
{
delete mpMyMap;
}
Get(std::wstring name)
{
return mpMyMap[name];
}
}
返回mpMyMap[名称];我得到一个错误,这个类型没有运算符[]。我该怎么办?括号运算符在地图上,而不是地图的指针上 Try:return*mpMyMap[name] mpMyMap是一个我看不出原因的指针,因此您需要取消对它的引用:
return (*mpMyMap)[name];
如果mpMyMap必须是动态分配的,请记住在析构函数中删除它,并防止复制MyClass或实现复制构造函数和赋值运算符
注意Get缺少一个返回类型,该返回类型应为MyType或MyType&。使用参数获取常量std::wstring&以避免不必要的复制,并且常量因为Get不会修改它。正确的语法是
MyType Get(std::wstring name)
{
return (*mpMyMap)[name];
}
您还可以将映射作为实例成员而不是指针
std::map<std::wstring,MyType> mMyMap;
这样,Get中的原始代码就可以工作了,并且可以摆脱MyClass构造函数和析构函数中的内存管理。使用
return (*mpMyMap)[name];
或
还有,这是什么
public ref class MyClass
//^^^^^^^^^^
另外,在您的案例中为Get MyType添加返回类型,因为mpMyMap是指针,第一个变量是
Get(std::wstring name)
{
return (*mpMyMap)[name];
}
第二
Get(std::wstring name)
{
return mpMyMap->operator[](name);
}
和GET应该有返回类型。< /P>不是本机C++,它是C++ + cli。为什么MPMYAP是指针?你需要它作为一个指针吗?你可能不需要。如果确实需要将其作为指针,则应使用智能指针类型将其包装为std::unique_ptr或boost::scoped_ptr。为什么在C++/CLI中使用std::map?为什么不使用System::Collections::Generic::Dictionary?您的父母可能放错地方了。是不是应该是*mpMyMap[name]?@Robᵩ 是 啊印刷错误。谢谢
Get(std::wstring name)
{
return mpMyMap->operator[](name);
}