Template error : undefined reference

最后都变了- 提交于 2019-12-11 15:12:04

问题


I am trying to create a class linkedList using template but when I compile it the IDE gives an error : undefined reference to `listType::add(int) I am not understanding why ?

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;
}

}

Struct.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);

}


回答1:


You can't have the implementation of templated classes and functions in the cpp file.

The code has to be in the header, so the including files can see the implementation, and instantiate the correct version with their template argument type.



来源:https://stackoverflow.com/questions/14400157/template-error-undefined-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!