stl - C++ Template:error: 'Node' is not a template type
巴扎黑
巴扎黑 2017-04-17 13:02:02
0
2
876
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,求解答!

巴扎黑
巴扎黑

全部回覆(2)
洪涛

用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]

改成

Node<T> *pNode = new Node<T>(); 

就可以透過編譯了(建議類別和模板用new分配記憶體好一點,因為new可以自動呼叫預設的建構函數,也內建了sizeof、型別轉換和型別檢查功能)

但是沒有因為Clion,不能試。 。應該是編譯器實作問題吧。 。

Ty80

模板
結構節點{

雷雷

};

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板