小编Pro*_*ude的帖子

使用结构指针的C ++分段错误

我有一个名为Dictionary的类,其中包含一个键值对,一个指向该键值对的指针以及一个保存字典大小的int值。

template<typename K, typename V>
class Dictionary
{
public:

V& operator[](K key);

private:

struct KeyValue
{
    K key;
    V value;
}; //the key-value pair struct

KeyValue* array; //pointer to an array of items (the key-value pairs)

int size; //size of the dictionary (i.e. the array size)
};
Run Code Online (Sandbox Code Playgroud)

我正在尝试重载此类的[]运算符,当这样做时,出现段错误错误

template<typename K, typename V>
V& Dictionary<K,V>::operator[](K key){
  for (size_t i = 0; i < size; i++) {
    if (key == array[i].key) {
      return array[i].value;
    }
  }
  array[size].value = 0;
  size++;
  return array[size-1].value; …
Run Code Online (Sandbox Code Playgroud)

c++ templates segmentation-fault

1
推荐指数
1
解决办法
50
查看次数

标签 统计

c++ ×1

segmentation-fault ×1

templates ×1