C - 返回字符串时的分割故障



我有这个类

#include "Room.h"
#include "Book.h"
#include <cstdlib>
#include <iostream>
static int book_counter = 100;
//Constructors
Book::Book() {
    for(int i = 0; i < 13; i++) {
        this->customer_name += 97 + rand() % 26;
    }
    this->arrival = rand() % 30;
    this->duration = 1 + (rand() % 10);
    this->ppl = 1 + rand() % 5;
    this->room = nullptr;
    this->book_code = book_counter++;
}
Book::Book(std::string nm, int arr, int dur, int ppl) {
    this->customer_name = nm;
    this->arrival = arr;
    this->duration = dur;
    this->ppl = ppl;
    this->room = nullptr;
    this->book_code = book_counter++;
}
//Methods
int Book::getArr() {
    return arrival;
}
int Book::getDur() {
    return duration;
}
int Book::getPpl() {
    return ppl;
}
void Book::anathesi(Room* x) {
    this->room = x;
}
int Book::getBookCode() {
    return book_code;
}
Room* Book::getRoom() {
    return room;
}
std::string Book::getCustomerName() {
    return customer_name;
}

包括字符串Getter方法getCustomerName()。当我通过第一个构造函数创建的实例在MAIN上调用此方法时,一切正常。另一方面,如果实例是通过第二个构造函数创建的,则该方法将导致分割故障。

看来customer_name的长度无限长,因此在我尝试返回时会导致分割错误。

该方法在main中使用以下代码:

cout << hotel.getBooks(i)->getBookCode() << " " << hotel.getBooks(i)->getCustomerName()
                             << " " << hotel.getBooks(i)->getRoom()->getRoomCode() << "n";

我是新来的C ,所以请尽可能多地详细说明我的错。

课程的标题文件:

#ifndef PROJECT_BOOK_H
#define PROJECT_BOOK_H
#include <string>
class Room;
class Book {
    protected:
        std::string customer_name;
        int book_code;
        int arrival;
        int duration;
        int ppl;
        Room* room;
    public:
        Book();
        Book(std::string nm, int arr, int dur, int ppl);
        void anathesi(Room* x);
        int getArr();
        int getDur();
        int getPpl();
        int getBookCode();
        std::string getCustomerName();
        Room* getRoom();
};
#endif //PROJECT_BOOK_H

在hotel.h:

private: std::vector<Book*> books;
public: Book* getBooks(int i);

在hotel.cpp中:

Book* Hotel::getBooks(int i) {
    return books[i];
}

找到了问题并将其修复。我正在使用此代码创建实例:

Book obj(onoma, afiksh - 1, meres, arithmos);

我说的是分割的。我将其更改为:

Book *obj = new Book(onoma, afiksh - 1, meres, arithmos);

并解决了问题。感谢您的时间和帮助。不幸的是,我真的不知道为什么会起作用,但是一切都可以正常运行。因此,我想我必须查看new文档。

相关内容

  • 没有找到相关文章

最新更新