【问题标题】:Undefined reference to `LinkedList<int>::push_front(int) [duplicate]对 `LinkedList<int>::push_front(int) 的未定义引用 [重复]
【发布时间】:2012-10-24 09:18:32
【问题描述】:

可能重复:
Why do I get “unresolved external symbol” errors when using templates?

LinkedList.h

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include<iostream>

template<class T> class LinkedList;

//------Node------
template<class T>
class Node {
private:
    T data;
    Node<T>* next;
public:
    Node(){data = 0; next=0;}
    Node(T data);
    friend class LinkedList<T>;

};


//------Iterator------
template<class T>
class Iterator {
private:
    Node<T> *current;
public:

    friend class LinkedList<T>;
    Iterator operator*();
 };

//------LinkedList------
template<class T>
class LinkedList {
private:
    Node<T> *head;


public:
    LinkedList(){head=0;}
    void push_front(T data);
    void push_back(const T& data);

    Iterator<T> begin();
    Iterator<T> end();

};



#endif  /* LINKEDLIST_H */

LinkedList.cpp

#include "LinkedList.h"
#include<iostream>


using namespace std;

//------Node------
template<class T>
Node<T>::Node(T data){
    this.data = data;
}


//------LinkedList------
template<class T>
void LinkedList<T>::push_front(T data){

    Node<T> *newNode = new Node<T>(data);

    if(head==0){
        head = newNode;
    }
    else{  
        newNode->next = head;
        head = newNode;
    }    
}

template<class T>
void LinkedList<T>::push_back(const T& data){
    Node<T> *newNode = new Node<T>(data);

    if(head==0)
        head = newNode;
    else{
        head->next = newNode;
    }        
}


//------Iterator------
template<class T>
Iterator<T> LinkedList<T>::begin(){
    return head;
}

template<class T>
Iterator<T> Iterator<T>::operator*(){

}

main.cpp

#include "LinkedList.h"

using namespace std;


int main() {
    LinkedList<int> list;

    int input = 10;

    list.push_front(input); 
}

您好,我是 C++ 新手,我正在尝试使用模板编写自己的 LinkedList。

我非常密切地关注我的书,这就是我得到的。我收到了这个错误。

/main.cpp:18: 对 `LinkedList::push_front(int)' 的未定义引用

我不知道为什么,有什么想法吗?

【问题讨论】:

标签: c++ templates undefined-reference


【解决方案1】:

您正在您的程序中使用模板。当你使用模板时,你必须将代码和头文件写在同一个文件中,因为编译器需要在程序中使用它的地方生成代码。

您可以这样做,也可以在main.cpp 中包含#inlcude "LinkedList.cpp"

这个问题可能会对你有所帮助。 Why can templates only be implemented in the header file?

【讨论】:

  • 您没有将所有内容都放在标题中。您也可以使用显式实例化。 (我不建议这样做。)
  • 包括 inlcude
猜你喜欢
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-12
  • 1970-01-01
相关资源
最近更新 更多