C++模板如何重载运算符和访问私有财产
C++ template how to overloading operator and accessing private property
我目前正在尝试实现一个简单的基于模板的链表,该链表在 C++11 中采用通用键/值对。元素应通过 += 运算符添加到列表中。代码如下所示:
列表
// Forward declarations
template<typename K, typename V>
class list;
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &list, const std::tuple<K, V> ele) {
if (!list.head) {
// list is empty
list.head = new element(ele, nullptr);
}
return list;
};
// Class definition
template<typename K, typename V>
class list {
private:
struct element {
const K key;
const V value;
element *next;
element(const std::tuple<K, V> tuple, element *ele) :
key(std::get<0>(tuple)),
value(std::get<1>(tuple)),
next(ele) { }
};
element *head = nullptr;
public:
friend list<K, V> &operator+=<>(list<K, V> &list, const std::tuple<K, V> ele);
};
我无法编译它。我是否必须将运算符的实现放入前向声明或类本身中?如果我把它放在前向声明中,就像在片段中一样,我似乎不能使用"list.head = new element(ele, nullptr(;"。错误:"元素"之前的预期类型说明符
如果我把它放到类本身中,我无法访问 list.head,即使它是朋友。
你应该只在类模板定义之前(在前向声明之后(保留函数模板的声明,以告诉编译器在 friend 声明中指定的operator+=
是一个模板。然后稍后定义它。例如
// Forward declarations
template<typename K, typename V>
class list;
// declaration of function template
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &l, const std::tuple<K, V> ele);
// Class definition
template<typename K, typename V>
class list {
...
friend list<K, V> &operator+=<>(list<K, V> &l, const std::tuple<K, V> ele);
};
// definition of function template
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &l, const std::tuple<K, V> ele) {
if (!l.head) {
// list is empty
l.head = new typename list<K, V>::element(ele, nullptr);
}
return l;
}
附注:
不要用名称命名参数
list
,这与类模板的名称冲突list
。element
是一个嵌套结构,operator+=
中您应该像typename list<K, V>::element
一样指定它。使用名称
list
(与std::list
相同(不是一个好主意。
住
相关文章:
- 运行时多态性 - 箭头运算符访问了错误的成员?
- 如果键不存在,使用 [] 运算符访问 STL Map 元素会添加新元素
- 通过 [] 运算符访问unordered_map时出错
- 为什么我不能使用 [] 运算符访问 nlohmann C++ JSON 库中的数组?
- 如何使用运算符 [] 访问结构的指定字段值
- 为什么在递增后使用 [] 运算符访问指针数组会返回错误地址的当前内存位置
- 如何使用字符串字符数组中的 ++ 运算符访问下一个字符串
- 将对象数限制为1可以使用点运算符访问静态成员的1
- 提升:使用运算符 [] 访问 bimap
- 为什么默认情况下使用 [ ] 运算符访问超出范围的矢量元素时,C++检测?
- 如何使用 offset 运算符访问字符串的字符,并且字符串位于字符串向量中
- 如何在 vim 中将访问时的向量转换为运算符 [ ] 访问
- 在C++中,我可以使用箭头运算符访问另一个运算符吗
- 无法使用运算符 [] 访问二维堆向量的元素
- 在指向 wstring 的指针上使用 [ ] 运算符访问元素
- 使用作用域运算符访问非静态成员变量
- 使用运算符[]访问一个函数中的字符串会影响C++中另一个函数的输出
- 何时使用 " . " 或 " -> " 运算符访问属性或成员函数?
- 通过运算符 [] 访问静态成员unordered_map
- 试图使用运算符[]访问std::map元素时编译器错误