【问题标题】:Array subscript operator for pointer map指针映射的数组下标运算符
【发布时间】: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


    【解决方案1】:

    正确的做法是:

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

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

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

    T*& operator[](const std::string& s)
    

    【讨论】:

    • 为什么是std::string s?为什么不std::string const &amp; s
    • 应该有 operator[] 的 const 和 non-const 方法
    • 感谢您的帮助 :D,但 *& 是什么意思以及为什么对参数使用 const 引用?
    • @LukeB。这是一个指针引用——方法返回的确切对象的别名,而不是它的副本。您通过引用传递以防止参数的额外副本。
    • 它不起作用顺便说一句,这个方法仍然在赋值行给我一个编译错误,它说cannot convert 'Bar*' to 'Bar**' in assignment|
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    相关资源
    最近更新 更多