我正在创建一个链接列表模板类。我能够在其中存储所有基本数据类型甚至结构。但是它不允许我在其中存储类。它给出的错误是“错误C2512'客户':没有适当的默认构造函数可用”。错误将我指向由MyLinkList.h中的节点struct组成的构造函数。帮助将不胜感激。
//MAIN FUNCTION
#include "pch.h"
#include <iostream>
#include <string>
#include "MyLinkList.h"
#include "Customers.h"
int main(){
std::string name = "Abdullah";
Customers c1(name);
MyLinkList<Customers> listA;
listA.insert(c1);
return 0;
}
//Linked List template header file
#pragma once
#include <iostream>
template <class t>
class MyLinkList {
private:
struct node {
t obj;
node *next;
node(t obj);
};
node *head, *tail;
public:
MyLinkList();
void insert(t obj);
node* searchGet(t obj);
void Delete(t obj);
void sort();
void display();
};
template <class t>
MyLinkList<t>::node::node(t obj) {
this->obj = obj;
this->next = NULL;
}
template <class t>
MyLinkList<t>::MyLinkList() {
head = tail = NULL;
}
template <class t>
void MyLinkList<t>::insert(t obj) {
node *newNode = new node(obj);
if (head == NULL) {
head = tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
}
template <class t>
typename MyLinkList<t>::node* MyLinkList<t>::searchGet(t obj) {
node *curr = head;
while (curr->obj != obj) {
curr = curr->next;
}
return curr;
}
template <class t>
void MyLinkList<t>::Delete(t obj) {
if (head != NULL) {
node *delNode = searchGet(obj);
if (delNode == NULL) {
std::cout << "\n\tData was not found in List..n";
}
else {
if (delNode == head) {
head = head->next;
delete delNode;
}
else if (delNode == tail) {
node *prevNode = head; //we will make this prevNode the tail
while (prevNode->next != delNode) {
prevNode = prevNode->next;
}
tail = prevNode;
tail->next = NULL;
delete delNode;
}
else {
node *prevNode = head; //we will link this with the delNode->next
while (prevNode->next != delNode) {
prevNode = prevNode->next;
}
prevNode->next = delNode->next;
delete delNode;
}
}
}
else {
std::cout << "\n\tThe List is Empty..\n";
}
}
template <class t>
void MyLinkList<t>::sort() {
node *nodeA = head;
node *nodeB;
while (nodeA != NULL) {
nodeB = nodeA->next;
while (nodeB != NULL) {
if (nodeB->obj < nodeA->obj) {
t temp = nodeA->obj;
nodeA->obj = nodeB->obj;
nodeB->obj = temp;
}
nodeB = nodeB->next;
}
nodeA = nodeA->next;
}
}
template <class t>
void MyLinkList<t>::display() {
node *curr = head;
while (curr != NULL) {
std::cout << curr->obj << std::endl;
curr = curr->next;
}
}
//Customer Header File
#pragma once
#include <iostream>
#include <string>
class Customers {
private:
std::string name;
int customerID;
static int id;
public:
Customers(std::string name);
friend std::ostream& operator<< (std::ostream& stream, const Customers& c);
};
//Customer.cpp file
#include "pch.h"
#include "Customers.h"
int Customers::id = 0;
Customers::Customers(std::string name) {
id++;
this->name = name;
this->customerID = id;
}
std::ostream& operator <<(std::ostream& stream, const Customers& c) {
return stream << "Name : " << c.name + "\nID : " << c.customerID << "\n";
}