【问题标题】:The default constructor cannot be referenced无法引用默认构造函数
【发布时间】: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


【解决方案1】:
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"};,而不是 () 作为参数。

【讨论】:

  • 哦,好吧,我不知道我不应该创建那种类型的构造函数,我什至不知道那种类型的声明Book b = {...}。它有很大帮助。我创建了构造函数,因为我需要从 .txt 文件中读取数据并且我不能使用 getline() 因为我将它保存到不同类型的结构变量中,并且我认为构造函数会帮助我。非常感谢您的回答。
  • @booboo 也可以做int day=0; 等;这些 ctor 可能很有用,但如果添加它们,默认 ctor 将被删除。
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
  • 2016-07-23
  • 2013-03-13
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多