gpt4 book ai didi

C++ 模板和重载下标运算符

转载 作者:行者123 更新时间:2023-11-30 05:36:30 25 4
gpt4 key购买 nike

I am trying to overload the subscript operator in order to use it to fill a template that is used in a map class.

这是模板结构

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

在这个类中使用

map 类

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];
};

我想重载下标运算符,以便我可以通过此函数调用将键和值放入 mNodeList。

类和运算符(operator)调用

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];
}

错误:

不允许非法索引

初始化无法从初始化器转换为节点

最佳答案

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

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;
}

关于C++ 模板和重载下标运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33543196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com