编译时我一直收到这个错误。我不确定我的模板构造函数是否有问题,或者我是如何插入类型'处理程序'进入双重链表。
./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的完整代码 - &gt; https://github.com/Cristianooo/Registrar-Simulator
答案 0 :(得分: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
,以避免从T
到Node<T>
的潜在隐式转换。
template<class T>
class ListNode {
public:
explicit ListNode(const T& data);
explicit ListNode(T&& data);
};
您的代码还在.h
文件中定义了非内联代码,这可能会在以后导致ODR违规。