我刚写了一个创建链表的简单程序。当我在一个文件(main.cpp)中编写整个程序时,程序编译并运行正常。但是,当我将程序分成头文件,实现文件和main时,它不起作用。我得到错误“对List :: AddNode(int)的未定义引用。我不明白为什么......
头文件
#ifndef LINKEDLIST_H_INCLUDED
#define LINKEDLIST_H_INCLUDED
#include <iostream>
using namespace std;
class List
{
public:
List();
void AddNode(int addData);
void DeleteNode(int deldata);
void PrintList();
private:
struct Node
{
int data;
Node* next;
};
Node* head;
Node* curr;
Node* temp;
};
#endif // LINKEDLIST_H_INCLUDED
List.cpp
#include <cstdlib>
#include <iostream>
#include "List.h"
using namespace std;
List::List()
{
head = nullptr;
curr = nullptr;
temp = nullptr;
}
void List::AddNode(int addData)
{
nodePtr n = new Node;
n->next = nullptr;
n->data = addData;
if(head !=nullptr)
{
curr = head;
while(curr->next!=nullptr)
{
curr = curr->next; //This while loop advances the curr pointer to the next node in the list
}
curr->next = n; //now the last node in the list points to the new node we created. So our new node is now the last node
}
else
{
head = n;
}
}
void List::DeleteNode(int delData)
{
Node* delPtr = nullptr; //created a deletion pointer and set it equal to nothing (it's not pointing to anything)
temp = head;
curr = head;
while(curr != nullptr && curr->data !=delData)
{
temp = curr;
curr = curr->next;
}
if(curr==nullptr)
{
cout << delData << " was not in the list \n"
delete delPtr;
}
else
{
delPtr = curr;
curr = curr->next;
temp->next = curr;
delete delPtr;
cout << "the value " << delData << "was deleted \n";
}
}
void List::PrintList()
{
head = curr;
while(curr!=nullptr)
{
cout<<curr->data<<endl;
curr = curr->next;
}
}
的main.cpp
#include <iostream>
#include <cstdlib>
#include "List.h"
using namespace std;
int main()
{
List crisa;
crisa.AddNode(5);
}
当我尝试调用函数AddNode时,我在main.cpp文件中收到错误。我不知道为什么,这可能是编译问题吗?