繁体   English   中英

C ++继承问题

[英]C++ inheritance problem

我正在尝试使用堆作为基类来实现左派树。 以下是heap.h的内容:

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:未解析的外部符号“public:void __thiscall myclass :: hello(int)”(?hello @?$ myclass @ H @@ QAEXH @Z)1> c:\\ users \\ meher anand \\ documents \\ visual studio 2010 \\ Projects \\ try \\ Debug \\ try.exe:致命错误LNK1120:1个未解析的外部

你能告诉我我现在哪里出错吗? 谢谢

模板未针对该类型进行实例化。 最简单的方法是从编译中删除.cpp,并将其包含在使用模板的cpp中。

另一个简单的答案是在.h中定义整个模板。

模板函数的处理方式与常规函数略有不同。 在您尝试使用它之前,编译器实际上不会编译该函数。 如果你尝试使用它的唯一地方是.cpp,其中函数的主体是未定义的,它假定它必须在其他地方编译并为链接器提供引用以便稍后填写。

在你的情况下,你在leftist.cpp中定义了函数的主体,但你没有在那里使用它,你在其他地方使用它。 如果你已经在.h文件中定义了它,那么在你尝试使用它的任何地方都可以使用该定义,一切都会很好。 如果您已经在leftist.cpp中的某处使用过函数,那么函数就会被创建,链接器会修复所有内容。

一般规则是在头文件中定义所有模板函数的主体。

每当你看到这个错误

错误LNK20XX未解析的外部符号

这意味着链接链接器时无法找到函数定义。 在你的情况下,这是错误的

希望这对你有所帮助。 如果您需要更多帮助,请与我们联系

PK

以下应该工作(用g ++测试):

// File: heap.hh --------------------------
template <class T>
class heap {
public:a
    virtual void init(T*) = 0;
    virtual void insert(T*) = 0;
    virtual T delete_min() = 0;
};

// File: leftist_tree.hh ------------------
#include "heap.hh"
template <class T>
class leftist_tree : public heap<T> {
private:
    T* root;
public:
    void init(T* ) {}
    void insert(T* ) {}
    T delete_min() {T a; return a;}
};

// File: leftist_node.hh ------------------
struct leftist_node {
    int value;
};

// File: leftist_main.cpp -----------------
#include "leftist_tree.hh"
#include "leftist_node.hh"

int main() {
    leftist_tree< leftist_node > mytree;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM