我正在學習C++,現在我正在使用Template。模板類型未定義
我試圖實現鏈表:
ListElement.hpp
#ifndef LIST_ELEMENT_HPP_
#define LIST_ELEMENT_HPP_
template <class Type> class SingleLinkedList;
template <class Type>
class ListElement
{
public:
ListElement(const Type element);
~ListElement(void);
public:
Type val;
ListElement* next;
};
#endif
ListElement.cpp:
#include "ListElement.hpp"
ListElement<Type>::ListElement(const Type element)
{
*next = NULL;
val = element;
}
ListElement<Type>::~ListElement(void)
{
}
我得到的錯誤ListElement.cpp相對於Type
:Type is undefined
。
我發現了很多關於如何實現鏈表但沒有使用分離的hpp和cpp的例子。
你知道我該如何解決這個錯誤?
最後的代碼(類和實施預處理之後)都有,如果你不使用特定的實例出現在同一個文件實施。 – chris
不使用單獨的源文件和頭文件?當你使用模板時,它並不真正起作用,因爲你的模板類的用戶需要_whole_類定義,並且包含了這些函數。 –
另外,你在構造函數中初始化'next'不會達到你期望的效果!它將'NULL'分配給_random_位置。你想'next = nullptr;'(或'next = 0;')將_pointer_設置爲NULL。 –