在结构上实现的 C++ 模板

标签 c++

此 C++ 代码有问题。我是用VC++6.0编译的。它给出错误“无法推断类型的模板参数”...问题出在 display 函数中。

代码如下:

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

template <class type>  
struct one
{
  type data;
  one *next;
};

one<int> *head, *temp, *mid, *del = NULL;

template <class type>
void athead(type value)    
{    
  one *node = new one;    
  node->data = value;    
  node->next = head;    
  head = node;
}

template <class type>
void add_at_tail(type value)   
{
  one *node = new one;   
  node->data = value;    
  node->next = NULL;

  if(head == NULL)
  {
    head = node;   
    temp = head;
  }

  while(temp->next != NULL)   
  {
    temp = temp->next;
  }

  if(temp != node)
  {
    temp->next = node;  
  }
}

template <class type>
void display()
{
  one<type> *temp = new one;
  temp = head;  
  cout << "\n\n" << endl;   
  while(temp != NULL)   
  {
    cout << " " << temp->data << " " << "->";
    temp = temp->next;
  }
  cout << "\n\n\n";
}

int main()
{
  int a, b, c;
  cout << "Enter the data: " << endl;
  cin >> a;
  add_at_tail(a);
  cout << "Enter the data: " << endl;
  cin >> b;
  add_at_tail(b);
  cout << "Enter the data: " << endl;
  cin >> c;
  add_at_tail(c);

  display();

  return 0;
}

最佳答案

这里至少有几个问题:

首先,你已经定义了模板函数:

template<class type>
void display()
{
    one<type> *temp=new one;
    temp=head;  
    cout<<"\n\n"<<endl;   
    while(temp!=NULL)   
    {
        cout<<" "<<temp->data<<" "<<"->";
        temp=temp->next;
    }
    cout<<"\n\n\n";
}

这一行格式不正确,因为one不是一个完整的类型(one是一个类模板)

one<type> *temp=new one;

你需要这样做:

one<type> *temp=new one<type>;

然后在客户端代码中,您尝试像这样调用函数模板:

display();

但是 display 是一个没有参数的函数模板,所以编译器无法推断出它的模板参数 type 的类型。您必须在调用点指定 type 的类型。

display<int>();

display() 的实现也存在逻辑错误。您实例化了 one 的单个拷贝,但不对其进行初始化。然后您尝试像它是一个链表一样对其进行迭代,但它不是——它只是您刚刚创建的一些未初始化的节点。您可能希望传入您尝试迭代的链表。沿着这些线的东西:

template<class type>
void display(const one<type>& head)
{
    one<type> const * temp = &head;
    cout<<"\n\n"<<endl;   
    while(temp!=NULL)   
    {
        cout<<" "<<temp->data<<" "<<"->";
        temp=temp->next;
    }
    cout<<"\n\n\n";
}

既然 display 接受了模板中提到的参数,编译器就能够推断出它的类型。你可能想这样调用它:

display(head);

关于在结构上实现的 C++ 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5833136/

相关文章:

c++ - 如何并行化这个结构?

c++ - find_if 函数构建问题

C++ 输入检查

python - 虚拟机如何渲染GUI?

c++ - C++ 中用户定义数组的问题

C++如何打印数组的元素但不重复?

c++ - 为什么在对象构造函数中抛出新表达式时不调用释放函数?

c++ - 资源句柄 - 禁止默认构造函数?

c++ - Motif:拦截关闭框事件并阻止应用程序退出? (C++)

c++ - 从 const 成员函数调用非常量成员函数指针