如何从函数返回指向模板类的指针?

时间:2015-06-18 11:52:43

标签: c++ templates pointers linked-list

#ifndef __linkedListH__
#define __linkedListH__

template<class T>
class Node
{
 public:
 T data;
 Node *next;
};

template<class T>
class linkedList
{
public:
    Node<T> *head;
    linkedList();
    Node<T>* returnHead();
    Node<T>* Insert(Node *head,T data);
};

template<class T>
linkedList<T>::linkedList()
{
    head = NULL;
}

Node* linkedList<T>::returnHead()
{
   return head;      
}

Node* linledList<T>::Insert(Node *head,int data)
{
 Node *newNode = new Node();
 newNode->data = data;
 newNode->next = NULL;  

 if(!head)
 return newNode;

 Node *temp = head;
 while(temp->next)
 {temp=temp->next;}

 temp->next = newNode;
 return head; 
 }

 #endif

在链接列表的这个实现中,请帮助我声明“returnHead”和“Insert”方法。当我从main函数调用这些方法时,我在声明这两种方法时遇到以下错误:

1.ISO C ++禁止声明'Node'没有类型 2.expected';'在'*'标记之前

1 个答案:

答案 0 :(得分:1)

您错过了一些template <class T><T>组件:

template <class T>
Node<T>* linkedList<T>::returnHead()
{
   return head;      
}

template <class T>
Node<T>* linledList<T>::Insert(Node<T> *head,int data)
{
 Node<T> *newNode = new Node<T>();
 newNode->data = data;
 newNode->next = NULL;  

 if(!head)
 return newNode;

 Node<T> *temp = head;
 while(temp->next)
 {temp=temp->next;}

 temp->next = newNode;
 return head; 
}

这需要在每个成员函数之前重复template声明标头,这是为什么类模板的成员函数通常在它们被声明的类中内联实现的原因之一。

另外,我认为参数data的类型应为T,而不是int。否则,它没有多大意义。

作为补充说明,您可能希望为Node类模板提供构造函数(使用nextdata),这样您就不必对其进行初始化来自外面。

无关的问题:包含两个连续下划线的名称(或以下划线后跟大写字母开头的下划线)保留给编译器&amp;标准库;将它们用于自己的东西是非法的。适当地重命名包括警卫。

相关问题