问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
#ifndef MYLIST_H
#define MYLIST_H
#include <iostream>
using namespace std;
template <class T>
struct ListNode
{
ListNode<T> *next;
T value;
ListNode(int n) : value(n), next(NULL) {}
};
template <class T>
class List
{
private:
ListNode<T> *head;
public:
List();
void createList1(int n);
void display();
};
//构造函数
template <class T>
List<T>::List()
{
head = new ListNode<T>;
head->next = NULL;
}
//创建元素为n个的链表,尾插法
template <class T>
void List<T>::createList1(int n)
{
for (int i = 0; i < n; i++)
{
T j;
cout << "请依次输入元素的值:" << endl;
cin >> j;
ListNode<T>* q = new ListNode<T>(j);
q->next = head->next;
head->next = q;
}
}
template <class T>
void List<T>::display()
{
ListNode<T> *p;
p = head->next;
while (p)
{
cout << p->value << endl;
p = p->next;
}
}
#endif
using namespace std;
int main()
{
List s1;
s1.createList1(3);
s1.display();
return 0;
}
运行结果及报错内容
./mylist.h:28:16: error: no matching constructor for initialization of 'ListNode'
head = new ListNode;
^
main.cpp:8:15: note: in instantiation of member function 'List::List' requested here
List s1;
^
./mylist.h:10:5: note: candidate constructor not viable: requires single argument 'n', but no arguments were provided
ListNode(int n) : value(n), next(NULL) {}
^
./mylist.h:6:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
struct ListNode
^
1 error generated.