【问题标题】:"class has no constructors" error for class template类模板的“类没有构造函数”错误
【发布时间】:2013-01-26 07:56:05
【问题描述】:

我正在制作一个链表,我只想在链表的前面添加一个节点。我做错了什么?

Node.h

 #pragma once

 namespace list_1
 {
template <typename T>
struct Node
{
    T data;
    Node<T> *next;

    // Constructor
    // Postcondition: 
    Node<T> (T d);
};

template <typename T>
Node<T>::Node(T d)
{
    data = d;
    next = NULL;
}
 }

list.h

template <typename T>
void list<T>::insert_front(const T& entry)
{
    Node<T> *temp = head;

    if(temp == NULL)
        temp->next = new Node(entry);
    else
    {
        while (temp->next != NULL)
        {
           temp = temp->next;
        }

        temp->next = new Node(entry);
    }
}

错误信息;

 1>------ Build started: Project: Linked List, Configuration: Debug Win32 ------
 1>  list_test.cpp
 1>c:\...\linked list\list.h(54): error C2955: 'list_1::Node' : use of class template requires template argument list
 1>          c:\...\linked list\node.h(7) : see declaration of 'list_1::Node'
 1>          c:\...\linked list\list.h(48) : while compiling class template member function 'void list_1::list<T>::insert_front(const T &)'
 1>          with
 1>          [
 1>              T=double
 1>          ]
 1>          c:\...\linked list\list_test.cpp(33) : see reference to class template instantiation 'list_1::list<T>' being compiled
 1>          with
 1>          [
 1>              T=double
 1>          ]
 1>c:\...\linked list\list.h(54): error C2514: 'list_1::Node' : class has no constructors
 1>          c:\...\linked list\node.h(7) : see declaration of 'list_1::Node'
 1>c:\...\linked list\list.h(62): error C2514: 'list_1::Node' : class has no constructors
 1>          c:\...\linked list\node.h(7) : see declaration of 'list_1::Node'
 ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

【问题讨论】:

  • 我不认为核心违规行 (list_test.cpp:33) 及其周围的代码也可以在这里发布?此外,Node 似乎位于其标头中的 list_1 命名空间中,但对于您选择从该文件发布的小 sn-p 代码,我在 list.h 中没有看到这样的命名空间包装器。
  • 我觉得你需要new Node&lt;T&gt;(entry);
  • 不应该像new Node(entry) 这样的东西是new Node&lt;T&gt;(entry)吗?
  • 你们摇滚.. 解决了它。
  • 我从来没有真正理解为什么编译器会这样做。 99% 的时间,您只关心 first 错误消息。此后的一切都可能毫无意义,因为第一个错误可能会导致更多无意义的错误。重点是 - 关注第一条错误消息并忽略其后的所有内容 - 至少在您的初始分析中。

标签: c++ insert linked-list


【解决方案1】:

阅读错误信息:

类模板的使用需要模板参数列表

new Node(entry) 应该是new Node&lt;T&gt;(entry)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    相关资源
    最近更新 更多