模板错误:未定义参考 [英] Template error : undefined reference

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

问题描述

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

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

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


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


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


main.cpp

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


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

}


推荐答案

您无法在cpp文件中实现模板化类和函数的实现.

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.

这篇关于模板错误:未定义参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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