为什么无法识别此模板类拥有的类的类型(使用模板类型)

Why is the type of this template-class-owned class, using a template type, unrecognized?

本文关键字:类型 识别 为什么 拥有      更新时间:2023-10-16

我希望这以前没有被某个问题所涵盖。我尽我所能地看起来,但我认为首先的部分问题在于我不明白发生了什么,这可能阻止了我找到以前的答案。如果是这样,我很抱歉,但除此之外...

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

下面是该类的一般结构:

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

我希望这一切都有所帮助,但如果还有其他需要,请问。谢谢大家。

问题出在以下几行:

*(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;
    }
}