我正在使用类模板在C ++中实现一个Ordered List数据结构。为简单起见,我实现了每个构造函数和函数内联。我为这个项目创建了自己的Node类。
编译器错误粘贴在此问题的底部。 "未定义对`Node :: ~Node()'"的引用。这是我第一次使用模板,我之前从未见过这个错误。我不知道从哪里开始。 任何帮助将不胜感激!
Node.h
#ifndef NODE_H
#define NODE_H
#include <iostream>
#include <cstdlib>
template <class E>
class Node {
public:
Node(const E init_data = NULL, Node<E>* init_link = NULL){data = init_data; link = init_link;}
Node(const Node<E>& orig){data = orig.getData(); setLink = NULL;}
virtual ~Node();
E getData() const{return data;}
void setData(E newData){data = newData;}
Node<E>* getLink(){return link;}
void setLink(Node<E>* nextLink) {link = nextLink;}
private:
E data;
Node<E>* link;
};
#endif /* NODE_H */
MyOrderedList.h
#ifndef MYORDEREDLIST_H
#define MYORDEREDLIST_H
#include <iostream>
#include <cstdlib>
#include "Node.h"
template <class E>
class MyOrderedList;
template <class E>
std::ostream& operator <<(std::ostream& out, const MyOrderedList<E>& list);
template <class E>
class MyOrderedList {
public:
MyOrderedList()
{/*IMPLEMENTATION*/}
MyOrderedList(const MyOrderedList<E>& orig)
{/*IMPLEMENTATION*/}
void operator =(const MyOrderedList<E>& orig)
{/*IMPLEMENTATION*/}
virtual ~MyOrderedList()
{/*IMPLEMENTATION*/}
bool remove(E data)
{/*IMPLEMENTATION*/}
MyOrderedList<E> kLargest(int k) const
{/*IMPLEMENTATION*/}
E get(int pos) const
{/*IMPLEMENTATION*/}
void insert(E data)
{/*IMPLEMENTATION*/}
MyOrderedList<E> operator +(const MyOrderedList<E>& list)
{/*IMPLEMENTATION*/}
friend std::ostream& operator <<(std::ostream& out, const MyOrderedList<E>& list)
{/*IMPLEMENTATION*/}
private:
Node<E>* head;
int size;
};
#endif //MYORDEREDLIST_H
的main.cpp
#include <cstdlib>
#include <iostream>
#include "MyOrderedList.h"
using namespace std;
int main(int argc, char** argv)
{
MyOrderedList<int> list;
list.insert(5);
std::cout << list << std::endl;;
return 0;
}
编译器错误
g++ -o dist/Debug/Cygwin-Windows/project7_windows build/Debug/Cygwin-Windows/main.o
build/Debug/Cygwin-Windows/main.o: In function `_ZN4NodeIiE7getLinkEv':
/cygdrive/c/Users/John/Desktop/Dropbox/Data Structures/Project7 Windows/MyOrderedList.h:(.rdata$_ZTV4NodeIiE[vtable for Node<int>]+0x8): undefined reference to `Node<int>::~Node()'
/cygdrive/c/Users/John/Desktop/Dropbox/Data Structures/Project7 Windows/MyOrderedList.h:(.rdata$_ZTV4NodeIiE[vtable for Node<int>]+0xc): undefined reference to `Node<int>::~Node()'
collect2: ld returned 1 exit status
make[2]: *** [dist/Debug/Cygwin-Windows/project7_windows.exe] Error 1
make [1]: * [.build-conf]错误2 make:* [.build-impl]错误2
答案 0 :(得分:0)
当您的编译器准确说明时,您声明了~Node()
但从未定义它。您需要提供Node::~Node()
的实现。
答案 1 :(得分:0)
此
class Node {
virtual ~Node();
};
声明(但没有定义)Node的虚拟析构函数(这里的模板性无关紧要)。你需要
class Node {
virtual ~Node() { /* put your dtor logic here */ }
};
不要害怕删除声明uless你计划继承Node,因为你不能在Node的dtor中加入太多逻辑:它对模板类型知之甚少。除非你打算删除指向下一个节点(Node::link
)的指针,这可能是一个危险的命题