【问题标题】:Templating C++ error模板化 C++ 错误
【发布时间】:2015-01-20 05:18:45
【问题描述】:

我正在编写与链表相关的代码,我想对整个程序进行模板化。这是我写的:

template<typename T>
class Node
{
public:
    T data;
    Node* next;
    Node(){};
};
class List{
public:Node<T>* head;
List() { head= NULL; } //constructor 

为此,它适用于我的其他功能。但是,我也在尝试编写一个函数 copy,它将列表复制到另一个。

List Copy(List copyme){
    List<T> x; 
    x = new List<T>;
    Node<T>* current = copyme.head;
    while (current != NULL){
        x.ListInsertHead(current->data);
        current = current->next;
    }
    x.ListReverse();
    return x;
    };

我收到关于模板类的错误,在这种情况下我应该写什么?谢谢。这些错误只是未声明的标识符,这是因为我错误地模板化了它。

【问题讨论】:

  • 您收到什么错误?请不要只告诉我们“错误”而忽略细节。
  • 如果这是一堵巨大的错误墙,请向我们展示第一个完整的错误。我们可以帮助您理解它在说什么。但前提是我们能看到它。
  • List 需要是带有参数T 的类模板。

标签: c++ templates linked-list


【解决方案1】:

试试这个:

template<typename T>
class Node
{
    public:
       T data;
       Node* next;
       Node(T val){ data = val; }
};

template <typename T>
class List
{
public:
       Node<T>* head;
       List() { head= NULL; } //constructor
};

template <typename T> 
List <T> Copy(List <T> copyme)
{
    List<T> x; 
    x = new List<T>;
    Node<T>* current = copyme.head;
    while (current != NULL){
        x.ListInsertHead(current->data);
        current = current->next;
    }
    x.ListReverse();
    return x;
}

【讨论】:

  • 我可以将输入参数更改为CopyList&lt;T&gt; const&amp; copyme
猜你喜欢
  • 2014-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-27
  • 1970-01-01
相关资源
最近更新 更多