未定义对类模板构造函数的引用 [英] Undefined reference to class template constructor

查看:231
本文介绍了未定义对类模板构造函数的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我试图制作一个通用的连续列表.这是List.h和List.cpp中的代码.在下面的List.cpp中,我仅显示了发生错误的构造函数.在main()中定义List < int > the_list时,出现错误未定义对List< int> :: List()的引用".

List.h

Hi,
I was trying to make a generic contiguous list. Here''s the code from List.h and List.cpp. In List.cpp below, I have only shown the constructor where the error is happening. When I define List < int > the_list in main(), I get an error "Undefined reference to List<int>::List()".

List.h

const int maxlist=1000;
enum Error_code
{
    success,
    overflow,
    underflow,
    range_error
};
template <class List_entry>
class List
{
    public:
    List();
    bool empty();
    bool full();
    int size();
    Error_code insert(int position, const List_entry &x);
    Error_code retrieve(int position, List_entry &x)const;
    Error_code replace(int position, const List_entry &x);
    Error_code remove(int position, List_entry &x);
    void traverse(void (*visit)(List_entry &x));//*visit is the pointer to function which performs operation on list
    protected:
    int count;
    List_entry entry[maxlist];
};



List.cpp



List.cpp

#include"List.h"
template <class List_entry>
List<List_entry>::List()
{
    count=0;
}

推荐答案

使用模板类时,需要将函数实现也放在头文件中,否则需要为每种类型显式声明类在cpp文件中. Visual Studio就是这种情况.我不知道它如何在GCC或其他编译器上使用.

无论如何,可以通过将函数实现移至头文件来进行尝试:)
when you are using template classes you need to put the function implementations in also in the header file.Otherwise you need to explicitly declare class for each type in cpp file. This is the case with visual studio. i don''t know how its on GCC or other compilers.

anyway give it a try by moving function implementations to header file :)


这篇关于未定义对类模板构造函数的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆