Я пытаюсь построить простое текстовое приключение для финальной недели.
Это довольно стандартные вещи. Используйте ‘n’, ‘e’, ’s’ и ‘w’, чтобы пройти через дом и попытаться добраться до конца лабиринта.
Некоторое время все шло хорошо, но я сталкиваюсь с проблемой, когда пытаюсь получить список доступных дверей.
Вот мои основные настройки
class Node
{
public:
//...
Node* getNLink() {return northLink;}
Node* getELink() {return eastLink;}
Node* getSLink() {return southLink;}
Node* getWLink() {return westLink;}
//...
void printAllPossibleMoves();
//checks all four links and tells the user which ones are not set to NULL
private:
//...
Node* northLink;
Node* eastLink;
Node* southLink;
Node* westLink;
const string dirNodeToStr(Node* dirNode);
//Takes a node pointer and returns whether that link is n/e/s/w, no spaces
};
Я уничтожил всех лишних членов.
Моя проблема связана с двумя функциями-членами в классе Node.
Во-первых, printAllPossibleMoves () получает список всех указателей, для которых не установлено значение NULL, и передает эти указатели в dirNodeToStr () по одному
void Node::printAllPossibleMoves()
{
Node* allDoors[4] = {getNLink(), getELink(), getSLink(), getWLink()};
//gets a list of all four pointers
Node* availableDoors[4];
int allDoorsLen(4), availableDoorsLen(0);
for(int i=0; i<allDoorsLen; i++)
{
if(allDoors[i] != NULL)
{
//filters out any NULL pointers and keeps track of the # of non-NULL pointers
availableDoors[i] = allDoors[i];
availableDoorsLen++;
}
}
if(availableDoorsLen == 0)
cout << "You don't see any doors in this room. Odd" << endl;
else if(availableDoorsLen == 1)
cout << "You see a door to the " << dirNodeToStr(availableDoors[0]) << endl; //CALL 1
else if(availableDoorsLen > 1 )
{
cout << "You see doors to the ";
for(int j=0; j<availableDoorsLen; j++)
{//make sure to put an 'and' in there before the last direction is printed
if(j == (availableDoorsLen-1))
cout << " and " << dirNodeToStr(availableDoors[j]) << endl; //CALL 2
else
cout << " " << dirNodeToStr(availableDoors[j]); //CALL 3
}
}
}
В трех отмеченных строках printAllPossibleMoves () передает один из указателей Node в dirNodeToStr (), где и проявляется ошибка.
const string Node::dirNodeToStr(Node* dirNode)
{
if(dirNode == dirNode->getNLink())
return "north";
else if(dirNode == dirNode->getELink())
return "east";
else if(dirNode == dirNode->getSLink())
return "south";
else if(dirNode == dirNode->getWLink())
return "west";
else
{
cout << "Error at Node::dirNodeToStr: Function was fed an invalid parameter" << endl;
//whenever this function is called, it falls through to this case
system("PAUSE");
exit(0);
}
}
И вывод:
This is the guest bedroom.
n
WEST HALL
This is a hallway.
You see doors to the Error at Node::dirNodeToStr: Function was fed an invalid pa
rameter
Press any key to continue . . .
И в случае, если это имеет значение, вот оригинальный вызов функции
void Node::movePlayer(Node*& pos, string direction)
{
if(direction == "north")
{
if(northLink == NULL)
cout << "You can't go north.\n";
else
{
pos = getNLink();
cout << pos->getRoomName() << endl << pos->getRoomInfo() << endl;
pos->printAllPossibleMoves();
}
}
//...
}
Так что ты думаешь? Почему указатели не совпадают? Я собрал все указатели, вставил их в другую функцию, а затем сравнил один из них со списком всех одинаковых указателей. Разве это не должно быть легким делом?
Этот код
for(int i=0; i<allDoorsLen; i++)
{
if(allDoors[i] != NULL)
{
//filters out any NULL pointers and keeps track of the # of non-NULL pointers
availableDoors[i] = allDoors[i];
availableDoorsLen++;
}
}
Вызывает ли NULL размещение в ваших доступных дверях, я думаю, вы можете это исправить, изменив строку
availableDoors[i] = allDoors[i]
к
availableDoors[availableDoorsLen] = allDoors[i]
Других решений пока нет …