【发布时间】:2015-11-05 11:17:01
【问题描述】:
我正在尝试重载下标运算符以使用它 填充在地图类中使用的模板。
这是模板结构
template<typename K, typename V>
struct Node
{
V Value;
K Key;
};
在这个类中使用
地图类
template<typename K, typename V>
class myMap
{
public:
myMap();
~myMap();
V& operator[] (const K Key);
private:
const int mInitalNumNodes = 10; //Start length of the map
int mNumOfNodes; //Count of the number of Nodes in the map
int mCurrentPostion;
Node<K,V> mNodeList[10];
};
我想重载下标运算符,以便我可以通过此函数调用将 Key 和 Value 放入 mNodeList 中。
类和操作员调用
myMap<char, int> x;
x[1] = 2;
我是如何在我的重载实现中不断出错的,你能指出我正确的方向吗?
运算符重载
template<typename K, typename V>
inline V& myMap<K, V>::operator[](const K Key)
{
// TODO: insert return statement here
Node<K, V> newNode;
newNode.Key = Key;
mNodeList[mCurrentPostion] = newNode;
mCurrentPostion++;
return mNodeList[&mCurrentPostion-1];
}
错误:
不允许非法索引
初始化无法从初始化程序转换为节点
【问题讨论】:
-
Node<K, V> newNode = {newNode.Key = Key,};Ehrm ... 什么? -
这个问题不是关于下标运算符,而是关于一个结构体初始化的问题。如果您相应地编辑标题并减少问题,您可能会得到更好的答案。 (即@SimonKraemer 指出的问题在另一种情况下也应该是一个问题。)
-
是的,我修好了,问题仍然是下标运算符不起作用
标签: c++ templates operator-overloading