【问题标题】:Return template object in template member function of template class在模板类的模板成员函数中返回模板对象
【发布时间】:2014-02-11 14:12:19
【问题描述】:

出于教育目的,我尝试实现标准容器之类的东西。但我坚持模板函数声明。需要语法方面的帮助

Error: error C2039: 'Begin' : is not a member of 'SinglyLinkedList<T>'. 

标题:

template<class T>
class SinglyLinkedList
{
public:
    typedef Iterator<T> Iterator;

    SinglyLinkedList();
    SinglyLinkedList(const SinglyLinkedList & other);
    ~SinglyLinkedList();

    bool IsEmpty() { return !m_pHead }

    void PushFront(T data);
    T & Front();
    void PopFront();
    void Clean();

    Iterator<T> Begin(); //Error
//  Iterator<T> End();
//  Iterator<T> Delete(Iterator<T> it);

private:
    Node<T> * m_pHead;
};

cpp 文件:

template<class T>
Iterator<T> SinglyLinkedList<T>::Begin()
{

}

编辑:

typedef Iterator<T> Iterator;

只是 typedef,所以我可以将 SinglyLinkedList::Iterator 用于 Iterator。我有迭代器类/它看起来像这样:

template<class T>
class Iterator
{
    friend SinglyLinkedList<T>;

public:
    Iterator() : m_pLinkedList(0), m_pNode(0) {}

    ~Iterator(){};

private:
    Iterator(SinglyLinkedList<T> * pLinkedList, Node<T> * pNode) : m_pLinkedList(pLinkedList), m_pNode(pNode) {}

    SinglyLinkedList<T> * GetListPtr() { return m_pLinkedList; }
    Node<T> * GetNodePtr() { return m_pNode; }

    void SetListPtr(SinglyLinkedList<T> * pList) { m_pLinkedList = pList; }
    void SetNodePtr(Node<T> * pNode) { m_pNode = pNode; }

    SinglyLinkedList<T> * m_pLinkedList;
    Node<T> * m_pNode;

public:
    //some overloaded operators

};

【问题讨论】:

  • 只是一个观察,但你需要使用SinglyLinkedList&lt;T&gt;::Iterator SinglyLinkedList&lt;T&gt;::Begin() {} 而不是你所拥有的
  • @CaptainObvlious Like 类型应该没问题,只要它们被正确考虑。 IE。类外定义可以使用Iterator&lt;T&gt;,类内decl可以使用Iterator::Iterator&lt;T&gt;See it live(或者我误解了你的说法)。无论如何,我会按照你描述的那样做,只是为了我自己的理智。
  • @WhozCraig 完全正确。假装它已被编辑成建议;)

标签: c++ templates


【解决方案1】:

类的模板成员的实现,必须在 .h 文件中,而不是在单独的 .cpp 文件中。每个翻译单元都需要知道实现,这样才能为每个不同的模板化调用创建正确的实例化。

另外,下面这行肯定是个问题

typedef Iterator<T> Iterator;

因为您为 typedef 使用模板化类的相同名称,这将产生未定义的行为。

【讨论】:

  • 传输到 h 文件并注释 typedef 有帮助。但是他们如何实现类似 list::Iterator?
  • 您的 typedef 的问题不是名称,您可以使用 Iterator,但在这种情况下,请使用不同的名称调用您的 Iterator 类,例如“Iterator_”,然后您将拥有: typedef Iterator_ 迭代器;并且编译器没有问题
猜你喜欢
  • 1970-01-01
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多