配列を解放しようとすると、このデバッグアサーションの失敗がデストラクタから引き続き発生します。答えは本当にシンプルなようですが、私はそれを理解できません。どんな助けもありがとう。 (ご想像の通り)私はそう簡単な説明は、あなたがnew[]
あなたがdelete[]
必要があり、素敵な:)アサーションのデバッグのエラー
// 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を使用します。あなたが新しい[]の場合、[]を削除する必要があります。 –