【问题标题】:C++ templates and overloading the subscript operatorC++ 模板和重载下标运算符
【发布时间】: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&lt;K, V&gt; newNode = {newNode.Key = Key,}; Ehrm ... 什么?
  • 这个问题不是关于下标运算符,而是关于一个结构体初始化的问题。如果您相应地编辑标题并减少问题,您可能会得到更好的答案。 (即@SimonKraemer 指出的问题在另一种情况下也应该是一个问题。)
  • 是的,我修好了,问题仍然是下标运算符不起作用

标签: c++ templates operator-overloading


【解决方案1】:

你的回报是错误的。你很可能想要

return mNodeList[mCurrentPostion - 1].Value;

而不是

return mNodeList[&mCurrentPostion-1];

MCVE:

template<typename K, typename V>
struct Node
{
    K       Key;
    V       Value;
};

template<typename K, typename V>
class myMap
{
public:
    myMap()
        :mCurrentPostion(0)
        ,mNumOfNodes(0)
    {}
    ~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];
};


template<typename K, typename V>
inline V& myMap<K, V>::operator[](const K Key)
{
    // TODO: insert return statement here if Key already exists
    Node<K, V> newNode;
    newNode.Key = Key;
    mNodeList[mCurrentPostion] = newNode;
    mCurrentPostion++;
    return mNodeList[mCurrentPostion - 1].Value;
}

int main()
{
    myMap<char, int> x;
    x[1] = 2;
}

【讨论】:

  • 我已经尝试过无法从 Node 转换为 int&,但我也想返回该数组位置,因为那是我想要分配值的节点你将被定位
  • 也许你应该更新你的问题并描述你想要实现的目标。如果可能的话,举个例子。 “我无法从 Node 转换为 int&” 如果 V 的类型为 int,它将起作用。我将更新我对 MVCE 的回答
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-03
相关资源
最近更新 更多