看了C++的单例模式后,启发很大,刚好要写一个List,就在想能不能用模板来实现List的Node节点。
在这里直接上重点,完成后的代码:
#ifndef DONZ_TEMPLATE_NODE_H
#define DONZ_TEMPLATE_NODE_H
template<typename SubNode>
class Node
{
public:
Node():last(nullptr), next(nullptr)
{
}
~Node(){}
public:
const SubNode * getLast();
const SubNode * getNext();
void setLast(SubNode* setLast);
void setNext(SubNode* setNext);
protected:
SubNode *last;
SubNode *next;
};
template<typename SubNode>
const SubNode *Node<SubNode>::getLast()
{
return last;
}
template<typename SubNode>
const SubNode *Node<SubNode>::getNext()
{
return next;
}
template<typename SubNode>
void Node<SubNode>::setLast(SubNode *const _last)
{
last = _last;
}
template<typename SubNode>
void Node<SubNode>::setNext(SubNode *const _next)
{
next = _next;
//_next -> setLas

本文探讨了如何使用C++模板来实现List的Node基类,以简化节点类的定义和减少代码重复。通过示例代码展示了模板在节省编写next和last指针相关操作上的优势。同时,文章也指出,虽然模板带来了便利,但在父类中使用子类可能存在的潜在问题,但针对Node类的情况,这种做法可能是可接受的。
最低0.47元/天 解锁文章
25

被折叠的 条评论
为什么被折叠?



