模板类中定义的类,不了解如何使用它并定义它

Class defined within template class, don't understand how to use it and define it

本文关键字:定义 何使用 不了解      更新时间:2023-10-16

我得到了一个我需要编码的模板的骨架。我从来没有真正处理过模板。这个模板的奇怪之处在于,它要求我们在模板本身中编写一个类 - 不仅仅是类函数,而是一个全新的类。这是仅用于模板的代码(我在某些方法中插入了几行代码只是为了开始,它们对我的问题无关紧要):

包括

template<class K, class V> class HMap
{
 private:
 // insert instance variables
 // insert constants (if any)
 public:
 class MapEntry
 {
    private:
        K key;
        V value;
    public:
    /**
     * Creates a MapEntry.
     * 
     * @param akey the key
     * @param avalue the value
     */
    MapEntry(K akey, V avalue)
    {
        key = akey;
        value = avalue;
    }
    /**
     * Returns the key for this entry.
     * 
     * @return the key for this entry
     */
    K getKey()
    {
        return key;
    }
    /**
     * Returns the value for this entry.
     * 
     * @return the value for this entry
     */
    V getValue()
    {
        return value;
    }
    /**
     * Sets the value for this entry.
     * 
     * @param newValue
     * @return the previous value for this entry
     */
    V setValue(V newValue)
    {
        V oldval;
        oldval = value;
        value = newvalue;
        return oldval;
    }
};

创建 HMap 模板类型的对象时,您将如何使用其中的 MapEntry 类?我对模板完全陌生,我有点迷茫,不知道从哪里开始。谢谢。

HMap<Int, Double>::MapEntry引用

内部类。但是为什么要暴露内部结构呢?

也许这样做会更容易(我实现对列表,而不是哈希,因为我很懒惰)

template <type Key, type Value>
class HashMap {
private:
struct entry { Key key, Value value};
std::list<entry> map;
public:
  HashMap() {};
  void add_element(Key key, Value value)
    {
      entry e = {.key = key, .value = value};
      map.push_back(e);
    };
}