template <class T>
struct Node{
T val;
Node *next;
Node(T &t){
this->val = t;
this->next = NULL;
}
};
template <class T>
class SingleList {
public:
SingleList();
~SingleList();
void push_front(T &t);
private:
int m_nListCount;
Node<T> *m_head;
};
template <class T>
SingleList<T>::SingleList(){
m_head = NULL;
m_nListCount = 0;
}
template <class T>
SingleList<T>::~SingleList(){
Node<T> *p, *pNext;
for (p = m_head; p != NULL ; p = pNext) {
pNext = p->next;
free(p);
}
m_nListCount = 0;
}
template <class T>
void SingleList<T>::push_front(T &t){
Node<T> *pNode = (Node<T> *)malloc(sizeof(Node<T>));
if(NULL != pNode){
pNode->val = t;
pNode->next = m_head;
m_head = pNode;
m_nListCount++;
}
}
代码全部放在头文件中,但是使用Clion编译提示:error: 'Node' is not a template type,求解答!
用vs2015试了下,可以编译通过。
但是在用g++在编译
Node<T> *pNode = (Node<T> *)malloc(sizeof(Node<T>));
这句时出现 error:there are no arguments to 'malloc' that depend on a template parameter, so a declaration of 'malloc' must be available [-fpermissive]
改成
就可以通过编译了(建议类和模板用new分配内存好一点,因为new可以自动调用默认的构造函数,还内置了sizeof、类型转换和类型安全检查功能)
但是没有因为Clion,不能试。。应该是编译器实现问题吧。。
template <class T>
struct Node{
};