2017-11-04 160 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违反非内嵌代码。

相关问题