C ++ - 返回字符串时出现分段错误

时间:2017-06-02 21:36:58

标签: c++ string segmentation-fault

我有这个班级

#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 ++的新手,所以请根据需要详细说明我的错误。

类Book的头文件:

#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];
}

1 个答案:

答案 0 :(得分:-1)

发现问题并修复它。 我用这段代码创建实例:

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

导致我说的分割。 我改为:

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

并解决了问题。谢谢你的时间和帮助。 不幸的是,我不知道为什么会这样,但确实如此,一切正常。因此,我想我必须查看new文档。