我想实现一个使用堆作为基类的左树。以下是heap.h的内容:C++继承问题
template <class T>
class heap {
public:
virtual void init(T*) = 0;
virtual void insert(T*) = 0;
virtual T delete_min() = 0;
};
以下是leftist.cpp的内容:
#include "heap.h"
template <class T>
class leftist_tree : public heap<T> {
private:
T* root;
public:
void init(T* a) {}
void insert(T* a) {}
T delete_min() {T a; return a;}
};
我使用的是下面的定义通过另一个类leftist_node作为参数传递给这个类:
leftist_tree<leftist_node> mytree;
我正在为函数init,insert和delete_min得到一个LNK 2001无法解析的外部符号错误。我究竟做错了什么?
编辑:
好吧,我在这一点上已经给出的例子是过于复杂。我试图在较小的范围内重现相同的错误,以便有人可以更容易地识别问题。我创建了以下示例文件。
try.cpp
#include "stdafx.h"
#include "myclass.h"
int _tmain(int argc, _TCHAR* argv[])
{
myclass<int> a;
a.hello(3);
return 0;
}
myclass.h
template <class T>
class myclass {
public:
void hello(T);
};
myclass.cpp
#include "myclass.h"
#include <iostream>
using namespace std;
template <class T>
void myclass<T>::hello(T a){
cout<<a<<endl;
system("pause");
}
我得到类似的错误消息:
1> try.obj :错误LNK2001:无法解析的外部符号l“public:void __thiscall myclass :: hello(int)”(?hello @?$ myclass @ H @@ QAEXH @ Z) 1> c:\ users \ meher和\ documents \ visual studio 2010 \ Projects \ try \ Debug \ try.exe:致命错误LNK1120:1个未解析的外部设备
你能告诉我现在我哪里出错了吗?由于
没有解决方案的工作。令人惊讶的是,当我没有从堆继承(只是将它声明为类leftist_tree {...}),我没有得到任何编译错误。 –
Anand
2010-10-02 01:14:18
我似乎无法重现错误。什么是'leftist_node'?是你的第三个代码块,mytree的定义,在与'leftist.cpp'相对应的编译单元中? – SingleNegationElimination 2010-10-02 01:21:19
始终将模板代码放在头文件中。在这种情况下,你在leftist.cpp中显示的内容应该在leftist.h中。此外,你的leftist_tree声明抛弃了'heap'方法的'virtual',所以确保你不要试图在'leftist'的子类中“覆盖”这些方法,否则会变得怪异。 – 2010-10-02 02:36:13