Неопределенная ссылка C ++ Ошибка при использовании класса List и класса Pair

В настоящее время я испытываю проблемы с добавлением пар в мою программу List, а затем выкладываю их, чтобы они работали в моей программе скремблирования, что означает поиск слов вроде boggle, но без заданного размера, и мне нужно сгенерировать слова / буквы ,

Этот код находится в моей программе scramble.cc.

List history;

bool placeAlreadyUsed(int x, int y, List history)
{
for(size_t i=0; i < history.getSize(); i++)
{
Pair p1 = history.get(i)
if(p1.r == x && p1.c == y)
return true;
}
return false
}

bool findUsersWord(string findThis, string alreadyFound, List &history, int maxR, int maxC)
{
// need to find the findThis  base case
if (findThis == alreadyFound)
cout << "SOLVED" << endl;
return true;

// need to find the first letter within the board and then progress around that.
if (alreadyFound.empty())
{
for (int rows = 0; rows < maxR; rows++)
for (int cols = 0; cols < maxC; cols++)
// find the each character within the
if (theBoard[rows][cols] == findThis[0])
{
alreadyFound = findThis[0];
Pair newR;
newR.r = rows;
newR.c = cols;
history.add(newR);
if (findUsersWord(findThis, alreadyFound, history, maxR, maxC))
return true;
else
{
// clear out the found Board
size_t temp = history.getSize()
for(size_t i=0; i<temp; i++
{
history.removeAt(i);
}
}
}
}
else
{
// try and find the next letters within the area around the base letter
// spin around the letter 3 * 3 grid
for (int x= (p1.r > 0 ? p1.r-1: p1.r); y <=(p1.r == (maxR-1) ? p1.r : p1.r+1);x++)
for (int y= (p1.c> 0 ? p1.c-1: p1.c); x<=(p1.c == (maxC-1) ? p1.c : p1.c+1);y++)
if ((board[x][y] == findThis[alreadyFound.length()]) && (!(x==p1.r && y==p1.c)))
// already used letter
if (!placeAlreadyUsed(y,x,history))
{
alreadyFound += findThis[alreadyFound.length()];
Pair newR;
newR.r = x;
newR.c = y;
history.add(newR, alreadyFound.length());
if (findUsersWord(findThis, alreadyFound, history, maxR, maxC))
return true;
else
{
if (alreadyFound.length() > 1)
alreadyFound = alreadyFound.substr(0, alreadyFound.length()-1);
history.removeAt(history.getSize()-1);
}
}
return false;
}
return false;
}

Мой list.cc — это проблема с этим кодом:

#include <iostream>
#include <cassert>
#include <cstdlib>
#include "list.h"
using namespace std;

List::Node::Node()
{
prev = next = NULL;
}

List:: List()
{
front = new Node()
rear = new Node()
front->next = rear;
rear->prev = front;

currentIndex=0;
current = front->next;
size=0;
}

List::~List()
{
_setCurrentIndex(0);
while(current)
{
Node *temp = current;
current = current -> next;
delete temp;
}
//not showing deep copy function b/c it isn't important for this program
void List::add(const ElementType & item, size_t index)
{
assert(0<=index && index <= size);
_setCurrentIndex(index);
size++;

Node *born = new Node;
born->data = item;
born->prev = current->prev;
born->prev->next = current;
born->prev = born;
current = born;
}

void List::removeAt(size_t index)
{
assert(0<=index<=getSize());
_setCurrentIndex(index);

Node *old = current;
current->prev->next = current->next;
current->next->prev = current->prev;
delete old;
size--;
}

void List::remove(const ElementType & item)
{
for(size_t i=0; i<size; i++)
{
_setCurrentIndex(i);
if(find(item)<getSize())
{
Node *tempOld = current;
current->next->prev = current->prev;
current->prev->next = current->next;
current = current->next;

delete tempOld;
size--;
}
}
}

size_t List::find(const ElementType & item) const
{
for(size_t i=0; i<size; i++)
{
_setCurrentIndex(i)
if(get(i) == item)
return i;
}
return getSize();
}

List::ElementType List::get(size_t index) const
{
assert(0 <= index < size);
_setCurrentIndex(index);
assert(current->next != NULL);
return current->data;
}

size_t List::getSize() const
{
return size;
}

void List::output(std::ostream & ostr) const
{
for(size_t i=0; i<size; i++)
{
_setCurrentIndex(i);
ostr << current->data << " ";
}
ostr << endl;
}

void List:: _setCurrentIndex(size_t index) const
{
int x;
if(currentIndex > index)
x = currentIndex - index;
else
x = index-currentIndex;

if(index < (sizez_t)x)
{
current = front->next;
curentIndex=0;
while(currentIndex != index)
{
current = current->next;
currentIndex++;
}
}
else if((size-index) < (size_t)x)
{
current = rear;
currentIndex = size;
while(currentIndex != index)
{
current = current->prev;
currentIndex--;
}
}
else
{
if(currentIndex > index)
{
while(currentIndex!=index)
{
current = current->prev;
currentIndex--;
}
}
else
{
while(currentIndex!=index)
{
current = current->next;
currentIndex++;
}
}
}
}

Я получаю ошибки
scramble.cc (.text + 0x480): неопределенная ссылка на List :: List (List const&)»
collect2: ld вернул 1 статус выхода
делать: * [Ошибка скремблирования 1

Есть идеи, что именно происходит и как подойти, чтобы это исправить?

РЕДАКТИРОВАТЬ: Я не пропускаю никаких включаемых заявлений, просто не помещал их в

0

Решение

Похоже, ваш list.h вероятно, объявляет конструктор копирования, List::List(List const&), и ваш scramble.cc пытается использовать это. Тем не менее, вы на самом деле не реализуете конструктор копирования в вашем list.cc файл, поэтому когда дело доходит до ссылки, конструктор копирования не найден. Вам нужно будет реализовать эту функцию где-то в list.cc:

List::List(List const& other)
{
// Implement this
}

Главный совет: когда вы получаете сообщение об ошибке, похожее на это (file.cc(.text+0x12AB) и упоминает ld), это означает, что у вас есть ошибка компоновщика. Это почти всегда, потому что вы пытаетесь использовать то, что вы объявили в одном модуле перевода, но никогда не определяли / не выполняли где-либо еще. Этап компиляции работает нормально, потому что часто ему нужно только найти объявление, чтобы составить правильно сформированную программу, но когда дело доходит до связывания вашей программы, компоновщик вылетает, потому что не может найти фактическую реализацию.

2

Другие решения

Хотя сообщается об ошибке, что вы объявили, но не реализовали конструктор копирования, реальный Проблема в том, что вы случайно пытаетесь сделать копию своего списка.

Вот где это происходит

bool placeAlreadyUsed(int x, int y, List history)

Измените это на постоянную ссылку, и ошибка должна исчезнуть.

bool placeAlreadyUsed(int x, int y, const List &history)

Объявление (но не реализация) конструктора копирования на самом деле является способом «предотвращения» случайного копирования вашего класса. повышение :: noncopyable использует похожую технику, делая конструктор копирования закрытым.

1

Вы должны включить list.h в ваш scramble.cc

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector