简体   繁体   English

如何为新结构分配内存?

[英]How to allocate memory for new structure?

I'm trying to allocate the memory for a new linked list within the constructor of a class, but when I try to compile it, I get some weird message. 我正在尝试在类的构造函数中为新的链表分配内存,但是当我尝试对其进行编译时,会收到一些奇怪的消息。

struct Node {
  Song s;
  Node *next = NULL;
};


tsuPod::tsuPod(int songs, int size)
{
  MAX_SONGS = songs;
  MAX_MEM   = size;
  memory = 0;
  Node *list = new Node; // call to implicitly deleted default constructor of Node
}

Seems like this should be a relatively quick response, as I'm guessing I'm missing something key to c++ and not necessarily making a syntax error. 似乎这应该是一个相对较快的响应,因为我猜想我缺少了c++某些关键内容,并不一定会导致语法错误。 To be honest, I didn't even know structs could have constructors, but apparently they can. 老实说,我什至不知道结构可以有构造函数,但显然它们可以。 Anyways, if someone could quickly tell me what's wrong or why it's saying then that you would be awesome! 无论如何,如果有人可以快速告诉我出了什么问题或为什么这样说,那么您真棒! Thank you! 谢谢!

As you didn't provide any constructor for Node , the default constructor for Node would be provided by the compiler. 当你没有为提供任何构造Node ,默认构造Node将被编译器提供。 But when it attempted to do so, it ran into a problem: To (default) construct a Node , you first need to construct a Song . 但是,当尝试这样做时,便遇到了一个问题:要(默认)构造一个Node ,您首先需要构造一个Song Creating a Song can be impossible for one of three reasons: 出于以下三个原因之一,可能无法创建Song

  1. All constructors for Song take one or more arguments, and you didn't provide a default value for them. Song所有构造函数都带有一个或多个参数,而您没有为其提供默认值。
  2. You explicitly deleted the default constructor: Song() = delete . 显式删除了默认构造函数: Song() = delete
  3. There is a default constructor, bt it's private. 有一个默认的构造函数,它是私有的。

That's why the error message also notes that the default constructor is implicitly deleted; 这就是为什么错误消息还指出默认构造函数被隐式删除的原因。 you can now rule out options #2 and #3. 您现在可以排除选项#2和#3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM