【问题标题】:Template error : undefined reference模板错误:未定义的引用
【发布时间】:2013-01-18 13:39:45
【问题描述】:

我正在尝试使用模板创建一个类linkedList,但是当我编译它时,IDE 给出了一个错误: 未定义对 `listType::add(int) 的引用 我不明白为什么?

linkedList.h

#ifndef LINKEDLISTS_H_INCLUDED
#define LINKEDLISTS_H_INCLUDED
#include "struct.h"
template <class type1>

class listType
{
public:

void add(type1);
void print();
private:
node<type1> *head;
};


#endif // LINKEDLISTS_H_INCLUDED

LinkedList.cpp

#include "linkedLists.h"
#include "struct.h"
#include <iostream>
using namespace std;

template <class type1>
void listType<type1>::add(type1 temp)
{
node<type1> *t;
t->value=temp;
t->link=head;
head=t;
}
template <class type1>
void listType<type1>::print()
{
node<type1> *p;
p=head;
while(p!=NULL)
{

    cout<<p->value<<endl;
    p=p->link;
}

}

结构体.h

#ifndef STRUCT_H_INCLUDED
#define STRUCT_H_INCLUDED
template <class type1>

struct node
{

type1 value;
node *link;
};


#endif // STRUCT_H_INCLUDED

main.cpp

#include <iostream>
#include "linkedLists.h"
using namespace std;


int main()
{
listType <int> test;
test.add(5);

}

【问题讨论】:

    标签: templates linked-list


    【解决方案1】:

    你不能在 cpp 文件中实现模板化的类和函数。

    代码必须在标头中,以便包含文件可以看到实现,并使用其模板参数类型实例化正确的版本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-15
      • 2010-11-09
      • 2021-12-21
      • 2021-10-22
      • 2012-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多