1

我有一个结构,里面有一个 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()行了。

我希望这很容易,因为我试图返回一个指针并且我正在存储一个指针。我的代码有什么问题?

4

1 回答 1

5

这样做的正确方法是:

T*& operator[](std::string s)
{
    return f[s];
}

并称它为f["key"] = new Bar().

编辑:您应该开始通过 const 引用传递非基本类型,您可以:

T*& operator[](const std::string& s)
于 2012-02-21T07:50:42.447 回答