[英]Debug assertion failure
I keep getting this debug assertion failure from my destructor when I try to free an array. 当我尝试释放数组时,我不断从析构函数中获得此调试声明失败。 The answer seems really simple but I can't quite figure it out.
答案似乎很简单,但我不太清楚。 Any help would be appreciated.
任何帮助,将不胜感激。 I'm a beginner (as you might have guessed) so a simple explanation would be lovely :)
我是一个初学者(您可能已经猜到了),所以简单的解释很可爱:)
// Class definitions
class Book {
public:
string title;
string author;
int pubYear;
};
class Library {
private:
Book *myBooks;
static int getBookIndex;
static int maxAmountOfBooks;
static int currentAmountOfBooks;
public:
void addBook(Book myBook);
Book getBook(void);
void showBooks(Library myLib);
Library();
~Library();
};
// Constructor
Library::Library() {
// Collecting user input
cout << "Number of Books: ";
cin >> maxAmountOfBooks;
cout << endl;
// Dynamically allocating memory
this->myBooks = new Book[maxAmountOfBooks];
cout << "Dynamically allocated library..." << endl;
}
// Destructor
Library::~Library() {
// Freeing the dynamically allocated memory
delete this->myBooks;
cout << "Freed dynamically allocated library..." << endl;
}
// Main
void main() {
// Creating a Book object
Book HarryPotter;
// Filling Book object fields
HarryPotter.title = "Harry Potter";
HarryPotter.author = "JK Rowling";
HarryPotter.pubYear = 1997;
// Printing out the Book object fields
cout << "Title: " << HarryPotter.title << endl;
cout << "Author: " << HarryPotter.author << endl;
cout << "Publication Year: " << HarryPotter.pubYear << endl << endl;
// Creating a Library object
Library myLib;
// Callling Library member functions
myLib.addBook(HarryPotter);
Book retBook = myLib.getBook();
// Printing out the Book object fields
cout << "Title: " << retBook.title << endl;
cout << "Author: " << retBook.author << endl;
cout << "Publication Year: " << retBook.pubYear << endl << endl;
}
Everything you new[]
you must delete[]
, delete
does not suffice. 您必须
delete[]
所有new[]
,但delete
还不够。
But the way more important piece of advice: 但是方式更重要的一条建议是:
Start using containers that are in the standard library instead of using dynamic memory allocation manually and praying it works. 开始使用标准库中的容器,而不是手动使用动态内存分配并祈祷它可以工作。 They're in the standard library for a reason, use them.
由于某种原因,它们位于标准库中,请使用它们。
std::vector
in this case. std::vector
在这种情况下。
At the end of the day you will be a happier person since you won't have to spend hours on debugging self-rolled containers. 最终,您将变得更快乐,因为您无需花费数小时来调试自卷式容器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.