2011-04-29 108 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>();固定所有的編譯器錯誤。