0
當我嘗試釋放數組時,我不斷從析構函數獲取調試斷言失敗。答案似乎很簡單,但我無法弄清楚。任何幫助,將不勝感激。我是一個初學者(正如你可能已經猜到了),這樣一個簡單的解釋將是可愛:)調試斷言失敗
// 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;
}
你正在釋放一個數組:'delete this-> myBooks' ==>'delete [] this-> myBooks'。 – CompuChip
請發表[mcve]:你的不完整,*因爲'addBook'和'getBook'的代碼缺失。它不是*最小的,*因爲'showBooks'永遠不會被調用。 – Angew
使用std :: vector。如果你新增了[],你必須刪除[]。 – 2017-06-22 11:38:20