c++ - 构造函数必须显式初始化没有默认构造函数的成员

标签 c++ class templates instantiation

编译时,我一直收到此错误。我不确定我的模板构造函数是否有问题,还是不确定如何将“handler”类型插入到双向链接列表中。

./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

最佳答案

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。

关于c++ - 构造函数必须显式初始化没有默认构造函数的成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47107291/

相关文章:

c++ - 斯坦福 C++ 库映射 vector 错误

C++ 列表插入迭代器超出范围

c++ - 如何显示类中某些内容的枚举值?

delphi - Delphi Win32 中的类帮助器和字符串

c++ - 当你完美转发时,typename T 变成 T& 或 T&&,但当你不这样做时,T 根本不是引用。如何?

c++ - 我可以使用 std::stack 作为对象池容器吗?

c++ - Richedit Msftedit奇怪的边框

json - 如何在模板之间传递变量 - ARM json

jquery - 根据容器 div 宽度向 <li> 元素添加类

c++ - 在完全专用的类模板中初始化静态成员