2013-02-26 37 views
-1

請看看下面的代碼模板鏈接列表:任何成員提供錯誤

LinkedList.h

template <typename T> 

class LinkedList 
{ 
public: 
    T *first; 

    LinkedList() 
    { 
     first = 0; 
    } 
    ~LinkedList(){} 


    T *Delete() 
    { 
    } 

    T *Delete(const int key) 
    { 
    } 

    void Display() 
    { 
    } 

    T *Find(const int key) 
    { 
    } 

    void Insert(T* newLink) 
    { 
     //newLink->next = first; 
     //first = newLink; 
    } 

    bool IsEmpty() 
    { 
     return (first==0); 
    } 
}; 

Weapon.h

#pragma once 
#include "GameObject.h" 
#include "Stack.h" 
#include "Round.h" 

class Weapon : 
    public GameObject 
{ 
public: 
    Weapon(int); 
    ~Weapon(void); 

    Stack <Round> stack1; 
    Weapon *next; 

    void Display(); 
}; 

武器。 cpp

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

using namespace std; 

Weapon::Weapon(int size) : stack1(size) 
{ 

} 


Weapon::~Weapon(void) 
{ 
} 

在這裏,武器代表鏈接列表中的鏈接。 Next是指向列表中下一個武器的指針。但是我怎樣才能訪問它?我嘗試在鏈接列表的Insert()方法不起作用。我評論過他們。請幫忙!

+0

你是什麼意思的「沒有工作」? – us2012 2013-02-26 22:35:01

+0

@ us2012:我不能指向'下一個'。 intellisense說沒有會員可用。 – 2013-02-26 22:47:47

回答

1
void Insert(T* newLink) 
    { 
     //newLink->next = first; 
     //first = newLink; 
    } 

因爲T是模板類型,所以不會「工作」。它可能包含也可能不包含「下一個」元素。這是使用模板的錯誤方法。

T應該是由LinkedList ..而不是LinkedList本身持有的數據類型。

#include <iostream> 
using namespace std; 

template <typename T> 
class LinkedList 
{ 
    struct Node { 
    T data; 
    struct Node *next; 
    }; 

    Node *head,*tail; 

    void init(T& data) 
    { 
    if(head == NULL){ 
     head = new Node; 
     head->data = data; 
     head->next = NULL; 
     tail = head; 
    } 
    } 
public: 
    LinkedList() 
    { 
    head = NULL; 
    tail = NULL; 
    } 
    LinkedList(T& data) 
    { 
    head = NULL; 
    tail = NULL; 
    init(data); 
    } 

    ~LinkedList() 
    { 
    deleteLinkedList(head); 
    } 

    bool IsEmpty() 
    { 
    if(head == NULL) return true; 
    return false; 
    } 

    void Display() 
    { 
    for(Node *h = head; h != NULL; h=h->next){ 
     cout << h->data; 
    } 
    } 

    void Insert(T data) 
    { 
    if(this->IsEmpty()){ 
     init(data); 
     return; 
    } 
    Node *n = new Node; 
    n->data = data; 
    n->next = NULL; 
    tail->next = n; 
    tail = n; 
    } 

    void deleteLinkedList(Node *hd) 
    { 
    if(hd->next == tail){ 
     delete tail; 
     tail = hd; 
     return; 
    } 
    deleteLinkedList(hd->next); 
    } 
}; 

int main(int argc, char *argv[]) 
{ 
    LinkedList<int> list; 
    list.Insert(10); 
    list.Insert(20); 
    list.Insert(30); 
    list.Display(); 
    return 0; 
} 
+0

噢男人,我想我很麻煩!那麼如何解決它?請幫忙。新的C++! – 2013-02-27 05:33:27

+0

你的意思是我需要將LinkedList中的「T」變成「武器」? insert()中的「T」? – 2013-02-27 05:48:36

+0

@Yohan看到編輯 – 2013-02-27 05:56:35