2011-04-29 152 views
0

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

下面的代码:

#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; 
} 
+0

这看起来像家庭作业。是吗? – 2011-04-29 14:21:32

回答

0

你得display()一个电话,但这是一个模板函数,你已经给编译器没有办法来推断模板参数。你可以明确地指定为display<int>();(但代码除此之外还有其他问题 - 你在几个地方写one,你应该写one<type>)。

0

那么,由于display()没有参数,你认为编译器如何确定你期望type被指定为什么类型?你可以给display()一个虚拟的类型参数,或者,最好将所有这些方法移到一个类中,这样整个程序中的类型参数就可以被计算出来。

1

夫妇在此问题,至少:

首先,你必须定义模板功能:

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); 
0

更换one *node = new one;one<type>* node = new one<type>;main()改变display();display<int>();固定所有的编译器错误。