0

在我的主要功能中,我调用 inputHolding 5 次。它经历了几个循环,然后它给我一个错误,说当它尝试读取 callNumber 时堆已损坏,通常在第三个循环中。如何修复此崩溃?

Holding* inputHolding() {
char selection;
char title[50];
int callNumber = 0;
char author[50];
char performer[50];
char format;

cout << "Enter B for book, R for recording: ";
cin >> selection;

if (selection == 'B') {
    cout << "Enter book title: ";
    cin >> title;

    cout << "Enter book author: ";
    cin >> author;

    cout << "Enter call number: ";
    cin >> callNumber;

    Book* muhbooksie = new Book(title, callNumber, author);
    return muhbooksie;
}
else  if (selection == 'R') {
    cout << "Enter recording title: ";
    cin >> title;

    cout << "Enter performer: ";
    cin >> performer;

    cout << "Enter format: (M)P3, (W)AV, (A)IFF: ";
    cin >> format;

    cout << "Enter call number: ";
    cin >> callNumber;

    Recording* muhbooksie = new Recording(title, callNumber, performer,     format);
    return muhbooksie;
}
else {
    cout << "Incorrect selection" << endl;
    return nullptr;
}
}

书.cpp:

#include <iostream>
#include "Holding.h"
#include "Book.h"
#include "String.h"

using namespace std;

Book::Book() {

}

Book::Book(const Book& copy) : Holding(copy) {
author = new char[strlen(copy.author) + 1];

strcpy_s(author, sizeof(author), copy.author);
}

Book::Book(char* inputTitle, int inputCallNum, char* inputAuthor) : Holding(inputTitle,     inputCallNum) {
int len = strlen(inputAuthor) + 1;
author = new char[len];

strcpy_s(author, sizeof(author)*len, inputAuthor);
}

Book::~Book() {
delete [] author;
}

void Book::print() {
cout << "BOOK: " << author << " " << title << " " << callNumber << endl;
}
4

1 回答 1

1

有了问题评论部分中所说的一切,您应该(对于 Book 类):

  • 重载“=”运算符,
  • 实施“复制和交换”习语,
  • 并在默认构造函数的 nullptr 处初始化 'author' 并检查析构函数中的值。

这样,您的代码将更干净,例如,如果使用默认构造函数,则析构函数不会删除未指定的作者。

于 2013-07-26T12:19:33.900 回答