【发布时间】:2012-03-11 13:07:06
【问题描述】:
我有一个结构,里面有一个 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"。
我希望这很容易,因为我正在尝试返回一个指针并且我正在存储一个指针。我的代码有什么问题?
【问题讨论】:
标签: c++ arrays pointers map subscript