Ins*_*nct 2 c++ templates undefined-reference
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 */
Run Code Online (Sandbox Code Playgroud)
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*(){
}
Run Code Online (Sandbox Code Playgroud)
main.cpp中
#include "LinkedList.h"
using namespace std;
int main() {
LinkedList<int> list;
int input = 10;
list.push_front(input);
}
Run Code Online (Sandbox Code Playgroud)
嗨,我在c ++上相当新,我正在尝试使用模板编写自己的LinkedList.
我非常仔细地跟着我的书,这就是我得到的.我收到这个错误.
/main.cpp:18:对"LinkedList :: push_front(int)"的未定义引用
我不知道为什么,任何想法?
您正在使用程序中的模板.使用模板时,必须在同一文件中编写代码和标头,因为编译器需要生成在程序中使用它的代码.
你可以做这个或包括 #inlcude "LinkedList.cpp"在main.cpp
这个问题可能对你有帮助. 为什么模板只能在头文件中实现?
| 归档时间: |
|
| 查看次数: |
3219 次 |
| 最近记录: |