【发布时间】:2017-06-02 21:36:57
【问题描述】:
我有这门课
#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];
}
【问题讨论】:
-
摆脱所有
this的使用——它们不是必需的,使代码难以阅读,而且你甚至不能始终如一地使用它们。 -
您确定
hotel.getBooks(i)返回一个指向有效Book的指针吗? -
@AQUATH 无处不在。几乎从不需要显式使用
this。 -
仅仅因为 C++ 程序在特定行崩溃并不意味着这就是错误所在。返回字符串的方式没有任何问题。错误可能出现在任何地方,这就是为什么需要完全可重现的minimal reproducible example。欢迎使用 C++!
-
调试器告诉你的只是你程序崩溃的地方。正如我所解释的,这与“这就是错误所在”不同。我可以简单地编写一个递归函数,它会在整个堆栈中乱码,但返回正常,并且崩溃将发生在函数的调用者的调用者中,在代码的某些不相关部分中。那就是它会崩溃的地方,这就是调试器将向您显示该行的地方。但这不是错误所在。您可以重现崩溃真是太好了。但是,如果您希望其他人为您解决问题,他们也必须这样做。不可能,没有minimal reproducible example。
标签: c++ string segmentation-fault