Luk*_* B. 1 c++ arrays pointers map subscript
我有一个带有std ::指针映射的结构体.我正在尝试执行以下操作:
template <class T>
struct Foo
{
std::map<std::string, T*> f;
T& operator[](std::string s)
{
return *f[s];
}
}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它:
Foo<Bar> f;
f["key"] = new Bar();
Run Code Online (Sandbox Code Playgroud)
但它写的方式,它崩溃了程序.我也尝试过这样:
T* operator[](std::string s)
{
return f[s];
}
Run Code Online (Sandbox Code Playgroud)
但它没有编译.它说"lvalue required as left operand of assignment"就f["key"] = new Bar()行了.
我希望它很容易,因为我正在尝试返回一个指针而我正在存储一个指针.我的代码出了什么问题?
这样做的正确方法是:
T*& operator[](std::string s)
{
return f[s];
}
Run Code Online (Sandbox Code Playgroud)
并称之为f["key"] = new Bar().
编辑:你应该开始通过const引用传递非基本类型,你可以:
T*& operator[](const std::string& s)
Run Code Online (Sandbox Code Playgroud)