我和伙伴在我们的Text Adventure游戏中遇到了解析器问题。我们不断得到"分段错误(核心转储)"并且"在抛出' std :: out_of_range'的实例后终止调用 what():basic_string :: substr 流产(核心倾销)"错误,我们不知道热修复它。
void nextTurn(Player *player)
{
string input;
Parser *parser;
cout << player -> getName() << "'s turn: ";
cin >> input;
parser -> parse(input);
delete parser;
}
这是我们从主课程中的玩家获得每个玩家每回合想要的内容的输入。这是我们的Parser.cpp classe。
#include <iostream>
#include "Parser.h"
using namespace std;
/**
* Construct a new parser class
*/
Parser::Parser(Player *p, TownArea *t)
{
Parser::player = p;
Parser::townArea = t;
}
/**
* Parse the input text
*/
void Parser::parse(string input)
{
string action = input.substr(0, input.find(" "));
//Look around the room
if(action == "look" || action == "help")
{
cout << "Current Room: " << Parser::townArea -> getName() << endl;
cout << Parser::townArea -> getDescription() << endl;
return;
}
//See player's inventory
if(action == "inventory" || action == "inv")
{
vector<string> inventory = Parser::player -> getInventory();
if(inventory.size() == 0) cout << "Inventory is empty." << endl;
else
{
cout << "Inventory: " << endl << "| ";
for(int i = 0; i < inventory.size(); i++)
{
cout << inventory[i] << " | ";
}
cout << endl;
}
return;
}
}
答案 0 :(得分:1)
Parser *parser;
cout << player -> getName() << "'s turn: ";
cin >> input;
parser -> parse(input);
您只是声明了Parser
类的实例。您无法使用new
构建它。未定义的行为。
答案 1 :(得分:1)
您永远不会分配Parser
:
void nextTurn(Player *player)
{
string input;
Parser *parser; // this points to nothing!!!!
parser = new Parser; // now it points to a Parser
cout << player -> getName() << "'s turn: ";
cin >> input;
parser -> parse(input);
delete parser;
}
但是,当你在函数末尾只是delete
时,就不需要使用指针。在这种情况下,只需使用正常的自动变量,如下所示:
void nextTurn(Player *player)
{
string input;
Parser parser; // Don't use a pointer!
cout << player -> getName() << "'s turn: ";
cin >> input;
parser.parse(input);
// no need to delete here
}
Player
可能也是如此。只需创建它的正常实例并通过引用传递它:
void nextTurn(Player& player) // pass reference
{
string input;
Parser parser; // Don't use a pointer!
cout << player.getName() << "'s turn: ";
cin >> input;
parser.parse(input);
// no need to delete here
}
希望有所帮助。