指针映射的数组下标运算符
Array subscript operator for pointer map
我有一个结构,里面有一个std::指针映射
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];
}
并将其称为CCD_ 3。
EDIT:您应该开始通过const引用传递非基本类型,您可以:
T*& operator[](const std::string& s)
相关文章:
- 一组值的零开销下标运算符
- 如何重载下标运算符 [] 以引用 2d STL 数组?
- 有什么理由不扩展 std::set 以添加下标运算符吗?
- 在继承的模板类中使用下标 [] 运算符
- 为什么函数的任何索引处的下标运算符在C++中总是返回1
- c++下标运算符到下级类向量
- 数组下标运算符 ([ ]) 对数组有什么作用?
- 双标具有下标运算符的原因是什么?
- 基成员的重载下标运算符
- SFINAE 为什么我没有检测到 std::vector 的下标运算符?
- 如何重载下标运算符以返回可以是左值的可选值?
- C++下标运算符的继承规则
- 使用带有下标运算符的赋值运算符将值分配给 std::map
- 如何从重载的下标 [] 运算符返回 std::unique_ptr&?
- 为下标运算符和函数调用运算符提供默认参数
- C++ 下标运算符
- 将类实例作为指针传递,并在此指针上使用过载的下标运算符
- 如何为模板类的下标运算符
- 如何在提升 lambda 中使用下标运算符
- "飞机"不提供下标运算符是什么意思"