2017-11-04 549 views
0

編譯時我不斷收到此錯誤。我不確定模板構造函數是否有問題,或者我如何將類型'處理程序'插入到雙向鏈表中。構造函數必須顯式初始化沒有默認構造函數的成員

./ListNode.h:14:3: error: constructor for 'ListNode<Handler>' must explicitly 
     initialize the member 'data' which does not have a default constructor 
       ListNode(T d); 
       ^
./doublyLinked.h:70:25: note: in instantiation of member function 
     'ListNode<Handler>::ListNode' requested here 
     ListNode<T> *node= new ListNode<T>(d); 
          ^
simulation.cpp:56:20: note: in instantiation of member function 
     'DoublyLinkedList<Handler>::insertBack' requested here 
               handlerList->insertBack(*handler); 
                  ^
./ListNode.h:9:5: note: member is declared here 
       T data; 
       ^
./handler.h:4:7: note: 'Handler' declared here 
class Handler 
    ^

繼承人的github上這裏爲完整的代碼 - > https://github.com/Cristianooo/Registrar-Simulator

回答

0

https://isocpp.org/wiki/faq/ctors#init-lists

不要寫

template <class T> 
ListNode<T>::ListNode(T d) 
{ 
    data=d; 
    next=NULL; 
    prev=NULL; 
} 

因爲T data不正確構造時ListNode<T>構造運行。

而是寫

template<class T> 
ListNode<T>::ListNode(const T& d) : data(d), next(0), prev(0) {} 

假設T有一個拷貝構造函數。

在C++ 11中,您應該使用nullptr並另外提供一種方法來放置數據而不使用右值引用進行復制。

template<class T> 
ListNode<T>::ListNode(T&& d) : data(std::move(d)), next(nullptr), prev(nullptr) {} 

此外,在C++ 11,你可能還需要標記這些構造爲explicit以避免潛在的隱式轉換從TNode<T>

template<class T> 
class ListNode { 
public: 
    explicit ListNode(const T& data); 
    explicit ListNode(T&& data); 
}; 

你的代碼還定義了.h文件,以後可能會造成ODR違反非內嵌代碼。

相關問題