基本上,我正在尝试为 C++ 制作模板映射/字典类(我知道这已经完成,假设我是受虐狂)。
我开始写这个骨架:
#pragma once
template <class T>
class AssArray
{
int _size;
int _position;
public:
AssArray(int size);
~AssArray(void);
const T& operator [](char* b) const;
T& operator [](char* b) const;
//I read this should be done sth like this when researching, though an explanation would be nice.
};
现在,我需要能够获取 (T=AssArray["llama"])、设置 (AssArray["llama"]= T) 和覆盖 (AssArray["llama"]= newT)。
这样做非常简单,只需循环等,这里真正的问题是运算符;
如果我使用 AssArray["llama"]= T,我应该如何将 T 的值放入运算符重载函数中?
我只找到了简单描述解决方案的解释,并不能真正理解。
请赐教。
最佳答案
您所要做的就是像这样更正您的签名:
const T& operator [](char* b) const;
T& operator [](char* b);
我已经从第二个运算符中删除了 const
限定符。
if I use
AssArray["llama"]=T
, how am I supposed to get the value of T into the operator overloading-function?
你不知道。您只需返回对新值应存储位置的引用,编译器将处理其余部分。如果 "llama"
不存在于数组中,您需要为其创建一个条目,并返回对该条目的引用。
关于c++ - 在 C++ 中重载模板类的 [] 运算符,get 和 set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840885/