2012-10-06 45 views
1

我希望这个问题在之前的某个问题中没有涉及。我尽我所能,但我认为首先问题的一部分是我不明白到底发生了什么,这可能阻止我找到以前的答案。我很抱歉,但如果是的话,但除此之外...为什么使用模板类型的此模板类拥有的类的类型无法识别?

对于练习模板和更好地理解C++和代码设计,我已经开始编写一个链接列表的实现(目前很简单),主要是模仿std ::名单。我一直在努力正确地实现迭代器,并在逻辑上实现其他组件,但是我碰到了一个障碍。我猜这是在某处使用模板语法,但我不确定。这可能只是一个愚蠢的错误。

下面是类的一般结构:

template <class T> 
class LinkedList { 
public: 
    LinkedList(); 
    class Iterator; 
    void push_front(const T&); 
    void push_back(const T&); 
    void pop_front(); 
    void pop_back(); 
    T& front(); 
    T& back(); 
    unsigned int size() const; 
    bool empty() const; 
    Iterator begin(); 
    Iterator end(); 
private: 
    struct ListNode; 
    ListNode* m_front; 
    ListNode* m_back; 
    unsigned int m_size; 
}; 

template <class T> 
class LinkedList<T>::Iterator { 
public: 
    Iterator(); 
    Iterator(const Iterator& rhs); 
    Iterator(ListNode* const& node); 
    Iterator operator=(const Iterator& rhs); 
    T& operator*(); 
    bool operator==(const Iterator& rhs) const; 
    bool operator!=(const Iterator& rhs) const; 
    Iterator operator++(); 
private: 
    ListNode* m_node; 
}; 

template <class T> 
struct LinkedList<T>::ListNode { 
    T* m_data; 
    ListNode* m_next; 
}; 

,这里是有问题的功能:

template <class T> 
void LinkedList<T>::push_front(const T&) { 
    if (m_front == NULL) { 
     m_front = new ListNode; 
     *(m_front->m_data) = T; 
     m_front->m_next = NULL; 
     m_back = m_front; 
    } else if (m_front == m_back) { 
     m_front = new ListNode; 
     *(m_front->m_data) = T; 
     m_front->m_next = m_back; 
    } else { 
     ListNode* former_front(m_front); 
     m_front = new ListNode; 
     *(m_front->m_data) = T; 
     m_front->m_next = former_front; 
    } 
} 

和错误由GCC 4.6.3给出:

linkedlist.hpp: In member function ‘void pract::LinkedList<T>::push_front(const T&)’: 
linkedlist.hpp:75:31: error: expected primary-expression before ‘;’ token 
linkedlist.hpp:80:31: error: expected primary-expression before ‘;’ token 
linkedlist.hpp:85:31: error: expected primary-expression before ‘;’ token 

我希望所有的帮助,但如果还有其他什么是可取的,请不要问。 谢谢大家。

回答

1

存在的问题是在这些线上:

*(m_front->m_data) = T; 

这是试图将类型分配给一个变量,这显然是不可能的。可能你想要一个命名的参数,并用这个参数来表示这个参数:

template <class T> 
void LinkedList<T>::push_front(const T& t) { 
    if (m_front == NULL) { 
     m_front = new ListNode; 
     *(m_front->m_data) = t; 
     m_front->m_next = NULL; 
     m_back = m_front; 
    } else if (m_front == m_back) { 
     m_front = new ListNode; 
     *(m_front->m_data) = t; 
     m_front->m_next = m_back; 
    } else { 
     ListNode* former_front(m_front); 
     m_front = new ListNode; 
     *(m_front->m_data) = t; 
     m_front->m_next = former_front; 
    } 
} 
+0

Gah!我只知道这会是一些小错误。随着模板和动态数据结构以及类的子类玩弄......我忘记命名一个参数。 但除此之外,非常感谢! – Orion

+0

@Orion:没问题。 : - ] – ildjarn