每次我在头文件中有一个类并且我在源文件中使用该类时,都会遇到相同的错误。不管是哪个班级或哪个项目。
我正在尝试将一个新节点插入到链表数据结构的头部。
现在我有一个非常简单的头文件main.h
:
namespace linkedlistofclasses {
class Node {
public:
Node();
Node(int value, Node *next);
//Constructor to initialize a node
int getData() const;
//Retrieve value for this node
Node *getLink() const;
//Retrieve next Node in the list
void setData(int value);
//Use to modify the value stored in the list
void setLink(Node *next);
//Use to change the reference to the next node
private:
int data;
Node *link;
};
typedef Node* NodePtr;
}
我的源文件main.cpp
如下所示:
#include <iostream>
#include "main.h"
using namespace std;
using namespace linkedlistofclasses;
void head_insert(NodePtr &head, int the_number) {
NodePtr temp_ptr;
//The constructor sets temp_ptr->link to head and
//sets the data value to the_number
temp_ptr = new Node(the_number, head);
head = temp_ptr;
}
int main() {
NodePtr head, temp;
//Create a list of nodes 4->3->2->1->0
head = new Node(0, NULL);
for (int i = 1; i < 5; i++) {
head_insert(head, i);
}
//Iterate through the list and display each value
temp = head;
while (temp !=NULL) {
cout << temp->getData() << endl;
temp = temp->getLink();
}
//Delete all nodes in the list before exiting
//the program.
temp = head;
while (temp !=NULL) {
NodePtr nodeToDelete = temp;
temp = temp->getLink();
delete nodeToDelete;
}
return 0;
}
我的问题是我得到了这些编译错误:
Undefined symbols for architecture x86_64:
"linkedlistofclasses::Node::Node(int, linkedlistofclasses::Node*)", referenced from:
head_insert(linkedlistofclasses::Node*&, int) in main.o
_main in main.o
"linkedlistofclasses::Node::getData() const", referenced from:
_main in main.o
"linkedlistofclasses::Node::getLink() const", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
如果我在不使用类的情况下运行代码,将所有内容都写入源文件main.cpp
,则没有问题。但是无论我如何编写一个类,我总是会得到这个错误的一些变体。