我在鏈表的末尾插入一個字符串。當我編譯我的文件時,我得到2個錯誤:在鏈表的末尾插入字符串
錯誤:'setData'未在此範圍內聲明 setData(* string_p);
錯誤:'getNext'未在此範圍內聲明 newNode = getNext();
然而,它們是在我使用它們(在上面的方法中定義)之前定義的,所以我不明白這個錯誤。
#include <iostream>
#include <string>
using std::string;
using std::cout;
using std::endl;
#define SUCCESS 0
#define FAIL 1
// Represents an entry object in the linked-list
class ListEntry
{
public:
explicit ListEntry();
explicit ListEntry(const char *string_p);
~ListEntry();
string getData();
void setData(const char* string_p);
void setData(string string);
ListEntry *getNext();
ListEntry *getPrevious();
ListEntry *prev_p; // pointer to previous entry in the linked-list
ListEntry *next_p; // pointer to next entry in the linked-list
private:
string data; // entry's string
};
// Represents the linked-list object
class List
{
public:
List();
~List();
bool printForward();
bool printReverse();
bool insert(const char *string_p);
private:
int entryCount; // number of entries present in the linked-list
ListEntry *head_p; // pointer to the first entry in the list
ListEntry *tail_p; // pointer to the last entry in the list
};
// ListEntry constructor
ListEntry::ListEntry()
{
this->prev_p = NULL;
this->next_p = NULL;
return;
}
// ListEntry constructor
ListEntry::ListEntry(const char *string_p)
{
this->data = string_p;
this->prev_p = NULL;
this->next_p = NULL;
return;
}
// List entry destructor
ListEntry::~ListEntry()
{
return;
}
// Return the stored string object
string ListEntry::getData()
{
return this->data;
}
// Set the internal string data from a char*
void ListEntry::setData(const char* string_p)
{
this->data = string_p;
}
// Set the internal string data from a string
void ListEntry::setData(string string)
{
this->data = string;
}
// Returns reference to the next entry in the list
ListEntry *ListEntry::getNext()
{
return this->next_p;
}
// Returns reference to the previous entry in the list
ListEntry *ListEntry::getPrevious()
{
return this->prev_p;
}
我的插入函數(低於上述方法在我的程序):
bool List::insert(const char *string_p)
{
// Please write the list insert function
//new node to be inserted
ListEntry* newNode = new ListEntry();
//List *newList = new List();
if(newNode == NULL)
{
cout << "FAILED";
}
else
{
setData(*string_p); //////ERROR HERE
if(this->head_p = NULL)
{
newNode = getNext(); //////ERROR HERE
newNode = this->head_p;
this->head_p = newNode; // newNode now points to the head node
this->entryCount++;
return SUCCESS;
}
else
{
ListEntry* temp = this->head_p;
while(temp -> next_p != NULL)
{
temp = temp -> next_p;
}
temp -> next_p = newNode;
this->entryCount++;
return SUCCESS;
}
}
}
另外,setData(* string_p);應該是setData(string_p); –
'setData'和'getNext'屬於'ListEntry',但您在屬於'List'的方法中使用'this'。你的意思是'newNode-> getNext();'和'newNode-> setData(string_p);'? –