我正在做一个学校项目,需要创建一个具有双向列表和结构的图书馆系统。我想实现构造函数以使代码更清晰。当我想为双向列表创建结构并使用来为列表元素保留存储空间时,就会出现问题new list_of_books
。我收到的错误消息是没有对Book :: Book()的匹配函数调用,并且无法引用默认的“ list_of_books”构造函数-该函数已删除。这是什么意思,我该如何解决?
struct User {
std::string name;
std::string surname;
User(std::string name, std::string surname)
: name(name), surname(surname) {}
};
struct Date {
int day;
int month;
int year;
Date(int day, int month, int year)
: day(day), month(month), year(year) {}
};
struct Book {
int id;
std::string title;
struct User author;
std::string cathegory;
struct Date hire_date;
struct User reader;
std::string others;
Book(int id, std::string title, std::string nameA, std::string surnameA, std::string cathegory, int day, int month, int year, std::string nameR, std::string surnameR, std::string others)
: id(id), title(title), author(nameA, surnameA), cathegory(cathegory), hire_date(day, month, year), reader(nameR, surnameR), others(others) {}
};
struct list_of_books {
struct Book book;
list_of_books* next;
list_of_books* prev;
};
void push(Book data) {
if (head == NULL) {
list_of_books* element = new list_of_books;
element->book = data;
element->prev = NULL;
element->next = NULL;
head = element;
} else {
list_of_books* curr = head;
while(curr->next != NULL) {
curr = curr->next;
}
list_of_books* element = new list_of_books;
element->book = data;
element->prev = curr;
element->next = NULL;
curr->next = element;
}
}
struct User {
std::string name;
std::string surname;
User(std::string name, std::string surname)
: name(name), surname(surname) {}
};
这个构造函数是有害的。您有一个聚合(即为其数据的类型)和一个仅按顺序重复成员的构造函数。
做这个:
struct User {
std::string name;
std::string surname;
};
并为您编写的所有其他构造函数重复上述步骤。
只按顺序重复这些参数的构造函数不是一件好事。
如果删除程序中的所有构造函数,程序将进行编译。
现在出了什么问题?通过创建构造函数,可以删除默认的无参数构造函数。
然后,当您new list_of_books
尝试使用的构造函数时Book
,它不存在。
请注意,在使用聚合时,{}
如果要在适当的位置构建它们,则必须使用大括号构建列表,例如Book b = {"The Bookiest Book", "Bob Smith"};
,而不是()
参数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句