我有一个结构,里面有一个 std::map 指针。我正在尝试执行以下操作:
template <class T>
struct Foo
{
std::map<std::string, T*> f;
T& operator[](std::string s)
{
return *f[s];
}
}
然后像这样使用它:
Foo<Bar> f;
f["key"] = new Bar();
但是按照它的编写方式,它会使程序崩溃。我也试过这样:
T* operator[](std::string s)
{
return f[s];
}
但它无法编译。它在 f["key"] = new Bar()
行上说 "lvalue required as left operand of assignment"
。
我希望这很容易,因为我正在尝试返回一个指针并存储一个指针。我的代码有什么问题?
最佳答案
正确的做法是:
T*& operator[](std::string s)
{
return f[s];
}
并像 f["key"] = new Bar()
那样调用它。
编辑:您应该开始通过 const 引用传递非基本类型:
T*& operator[](const std::string& s)
关于c++ - 指针映射的数组下标运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9373886/