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 listType
{
public:
void add(type1);
void print();
private:
node *head;
};
#endif // LINKEDLISTS_H_INCLUDED
LinkedList.cpp
#include "linkedLists.h"
#include "struct.h"
#include
using namespace std;
template
void listType::add(type1 temp)
{
node *t;
t->value=temp;
t->link=head;
head=t;
}
template
void listType::print()
{
node *p;
p=head;
while(p!=NULL)
{
cout<value< p=p->link;
}
}
Struct.h
#ifndef STRUCT_H_INCLUDED
#define STRUCT_H_INCLUDED
template
struct node
{
type1 value;
node *link;
};
#endif // STRUCT_H_INCLUDED
main.cpp
#include
#include "linkedLists.h"
using namespace std;
int main()
{
listType test;
test.add(5);
}
Answer
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.
No comments:
Post a Comment