首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >堆已损坏

堆已损坏
EN

Stack Overflow用户
提问于 2013-07-26 08:25:57
回答 1查看 5.8K关注 0票数 0

在我的主要函数中,我调用inputHolding 5次。它经历了几个循环,然后给出了一个错误:当堆试图在callNumber中读取时(通常是在第三个循环上),堆已经损坏。我怎样才能解决这场车祸?

代码语言:javascript
复制
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;
}
}

Book.cpp:

代码语言:javascript
复制
#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;
}
EN

回答 1

Stack Overflow用户

发布于 2013-07-26 12:19:33

在问题的注释部分中,您应该(对于Book类):

  • 使'=‘操作符过载,
  • 执行“复制和交换”的成语,
  • 并在默认构造函数中初始化'author‘at nullptr,并检查析构函数中的值。

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17876494

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档