我有一个结构,里面有一个 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];
}
但它不编译。它说"lvalue required as left operand of assignment"
就f["key"] = new Bar()
行了。
我希望这很容易,因为我试图返回一个指针并且我正在存储一个指针。我的代码有什么问题?