尝试制作自定义ArrayList, 第一个错误告诉我将Type Tamplate()添加到struct ListNode。
但是在遵循错误指令后,反而得到了新的错误。
“架构x86_64找不到符号
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
#include <string>
using namespace std;
template<typename T>
struct ListNode<T>{
T value;
ListNode<T>* next;
ListNode(T d,ListNode<T> *n){
value = d;
next = n;
}
};
template<typename T>
class LinkedList
{
public :
LinkedList();
LinkedList(const LinkedList<T>& another);
~LinkedList();
void copy(const LinkedList<T>& another);
void add(T value);
void remove(int index);
int get(int index) const;
bool isEmpty() const;
int size() const;
string toString() const;
void clear();
LinkedList<T>& operator = (const LinkedList<T>& another);
private :
ListNode<T>* x_front;
int x_size;
};
#endif // LINKEDLIST_H
.CPP
#include "linkedlist.h"
#include "strlib.h"
#include <string>
using namespace std;
template<typename T>
LinkedList<T>::LinkedList(){
x_front = NULL;
x_size =0;
}
template<typename T>
LinkedList<T>::~LinkedList(){
clear();
}
template<typename T>
LinkedList<T>& LinkedList<T>::operator = (const LinkedList<T>& another){
delete x_front;
copy(another);
return *this;
}
template<typename T>
void LinkedList<T>::copy(const LinkedList<T>& another){
ListNode<T>* anotherCurrent = another.x_front;
while(anotherCurrent!=NULL){
this->add(anotherCurrent->value);
anotherCurrent = anotherCurrent->next;
}
}
template<typename T>
void LinkedList<T>::add(T value){
if(x_front == NULL){
x_front = new ListNode<T>(value,NULL);
}
else {
ListNode<T>*current = x_front;
while(current-> next != NULL){
current = current -> next;
}
current->next = new ListNode<T>(value,NULL);
}
x_size++;
}
template<typename T>
void LinkedList<T>::remove(int index){
if(index==0){
x_front = x_front->next;
}
else {
ListNode<T>* current = x_front;
for(int indexNow = 0 ; indexNow < index -1 ; indexNow++){
current = current->next;
}
current -> next = current -> next -> next;
}
x_size--;
}
template<typename T>
bool LinkedList<T>::isEmpty() const {
if(this->x_size == 0){
return true;
}
else {return false;}
}
template<typename T>
void LinkedList<T>::clear(){
while(this->isEmpty() ==false){
remove(x_size-1);
}
}
template<typename T>
string LinkedList<T>::toString() const{
string mystring;
for(ListNode<T>*p = x_front; p!=NULL ;p = p->next){
mystring = mystring + " " + integerToString(p->value);
}
return mystring;
}
template<typename T>
int LinkedList<T>::size() const{
return (this->x_size);
}
答案 0 :(得分:0)
必须在头文件
中定义所有模板