我正在编写一个实现双向链表的程序。我的问题是,当我通过发出命令编译时
g++ -g -Wall DynamicSequenceVector.cpp DynamicSequenceVector.h main.cpp
我收到以下控制台输出
/tmp/cc6P5VZK.o: In function `main':
main.cpp:(.text+0x1a): undefined reference to `DynamicNode::DynamicSequenceVector<int>::DynamicSequenceVector(int)'
main.cpp:(.text+0x3a): undefined reference to `DynamicNode::DynamicSequenceVector<int>::~DynamicSequenceVector()'
main.cpp:(.text+0x4f): undefined reference to `DynamicNode::DynamicSequenceVector<int>::~DynamicSequenceVector()'
collect2: error: ld returned 1 exit status
我感觉这是我如何在 main.cpp 中导入文件的问题,因为如果我将 main 函数移动到 DyanmicSequenceVector.cpp 文件中,它编译得非常好。另外,当我用参数构造一个新对象时,我只会收到这些编译错误。
动态序列向量.h
#ifndef __DYNAMIC_VECTOR
#define __DYNAMIC_VECTOR
namespace DynamicNode {
template <class Type>
class DynamicSequenceVector {
private:
struct dynamicNode {
dynamicNode *previousLink;
dynamicNode *nextLink;
Type data;
int position;
};
int nodeCount;
int currentPosition;
dynamicNode *headNode;
dynamicNode *tailNode;
dynamicNode *currentNode;
dynamicNode *tempNode;
public:
DynamicSequenceVector();
DynamicSequenceVector(Type data);
~DynamicSequenceVector();
void appendNode(Type nodeData);
void accessData(int startingPosition, int endingPosition);
};
}
#endif
动态序列向量.cpp
#include <iostream>
#include "DynamicSequenceVector.h"
using namespace std;
using namespace DynamicNode;
template <typename Type>
DynamicSequenceVector<Type>::DynamicSequenceVector() {
nodeCount = 0;
currentPosition = NULL;
headNode = NULL;
tailNode = NULL;
currentNode = NULL;
}
template <typename Type>
DynamicSequenceVector<Type>::DynamicSequenceVector(Type nodeData) {
nodeCount = 1;
currentPosition = 0;
headNode = new dynamicNode;
headNode->previousLink = NULL;
headNode->nextLink = NULL;
headNode->data = nodeData;
headNode->position = 0;
currentNode =
}
template <typename Type>
DynamicSequenceVector<Type>::~DynamicSequenceVector() {
while(nodeCount != 0) {
tempNode = tailNode->previousLink;
delete tailNode;
tailNode = tempNode;
}
return;
}
template <typename Type>
void DynamicSequenceVector<Type>::appendNode(Type nodeData) {
if (currentPosition == 0) {
headNode = new dynamicNode;
headNode->data = nodeData;
headNode->position = 0;
headNode->previousLink = NULL;
headNode->nextLink = NULL;
} else {
tempNode = new dynamicNode;
tempNode->data = nodeData;
tempNode->previousLink = tailNode;
tempNode->position = nodeCount + 1;
tailNode->nextLink = tempNode;
tailNode = tempNode;
}
nodeCount++;
}
template <typename Type>
void DynamicSequenceVector<Type>::accessData(int startingPosition,
int endingPosition) {
cout << "Data accessed";
return 0;
}
主文件
#include <iostream>
#include "DynamicSequenceVector.h"
//using namespace std;
using namespace DynamicNode;
int main() {
DynamicSequenceVector<int> test();
DynamicSequenceVector<int> testingVector(5); // gives an error
//test = new DynamicSequenceVector<char>::DynamicSequenceVector();
std::cout << "Hello world!\n";
}