【发布时间】:2021-04-02 03:40:25
【问题描述】:
我正在做一个学校项目,我需要创建一个具有双向列表和结构的图书馆系统。我想实现构造函数以使我的代码更清晰。当我想为双向列表创建结构并使用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;
}
}
【问题讨论】:
-
TL;DR:如果您自己不定义构造函数,则只能免费获得默认构造函数。这回答了你的问题了吗? Is there an implicit default constructor in C++?
-
我不这么认为,我想要实现的解决方案是在 Book 结构中具有构造函数,但不要在 list_of_books 结构中使用它。我认为错误是因为 list 结构继承了 Book 结构的构造函数,但我没有使用它。所以我需要以某种方式在 list_of_books 结构中使用 Book 结构而不使用 book 构造函数。
-
您在
struct list_of_books中使用它,它有一个成员struct Book book;,您尝试通过list_of_books* element = new list_of_books;创建它。在创建list_of_books时,你想如何创建成员book?
标签: c++ c++11 struct constructor default-constructor