模板类中定义的类,不了解如何使用它并定义它
Class defined within template class, don't understand how to use it and define it
我得到了一个我需要编码的模板的骨架。我从来没有真正处理过模板。这个模板的奇怪之处在于,它要求我们在模板本身中编写一个类 - 不仅仅是类函数,而是一个全新的类。这是仅用于模板的代码(我在某些方法中插入了几行代码只是为了开始,它们对我的问题无关紧要):
包括
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);
};
}
相关文章:
- 在运算符重载定义中使用成员函数(const错误)
- C2011: 'Card':"类"类型重新定义(尽管使用了包含保护并且没有在文件中重新定义.cpp类)
- 对自定义类使用 std::hash<uint64_t>
- 为了从自定义目录使用 CMake,我需要做什么?
- 如何将result_of与函数类型定义一起使用
- 如何在cmake工具链文件中设置编译功能,以便已知的自定义编译器使用target_compile_features
- 在类定义和使用静态数据之外定义私有成员函数
- 精神:不能在其规则定义中使用x3::skip(skipper)[一些递归规则]
- const 数组,用于在数组长度定义中使用其元素或为模板参数提供值
- 在函数定义中使用特征库时,小数点不会按预期存储
- 在类定义中使用声明
- 在这个节点定义中,为什么我们在结构定义之后使用"Node"?
- C++ C2509 在讲师的定义中使用 try: - catch
- 使用派生类实例化基类,而不在对象定义中使用指针
- 在类定义中使用'this'
- 类型重定义错误(使用标头保护)
- 如何定义和使用小于2E-308的数字
- 在 C++ 中定义和使用离散概率密度函数
- MEMSET定义和使用
- 在类的成员函数定义中使用 (::)