2012-06-04 46 views
1

我試圖實現我自己的Set模板,並嘗試使用獨立工作的Queue模板進行廣度優先搜索時遇到問題。無法從一種數據類型轉換爲相同的?

奇怪的部分是,我嘗試編譯時在Set模板中出現此錯誤。爲什麼它不能從一個指針轉換爲不同的數據類型?

error C2440: '=' : cannot convert from 'Set<T>::Node<T> *' to 'Set<T>::Node<T> *' 
     with 
     [ 
      T=std::string 
     ] 
     Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast 
     c:\users\programming\Set\Set.h(96) : while compiling class template member function 'void Set<T>::print(Set<T>::Node<T> *)' 
     with 
     [ 
      T=std::string 
     ] 
     c:\users\programming\Set\main.cpp(13) : see reference to class template instantiation 'Set<T>' being compiled 
     with 
     [ 
      T=std::string 
     ] 

隊列類模板

template <typename T> 
class Queue 
... 
T* front() 
{ 
    if (first != NULL) 
     return first->item; 
    else 
     return NULL; 
} 

集類模板

template <typename T> 
Class Set 
... 
Queue<Node<T> *> q; 
void print(Node<T> *p) 
{ 
    q.push(p); 
    while (p != NULL) 
    { 
     cout << p->item << "(" << p->height << ") "; 
     if (p->left != NULL) 
      q.push(p->left); 
     if (p->right != NULL) 
      q.push(p->right); 
     if (!q.size()) 
     { 
      // Error is at this line 
      p = q.front(); 
      q.pop(); 
     } 
     else 
      p = NULL; 
    } 
    cout << endl; 
} 
+2

_cannot從轉換 '設置 ::節點 *' 到 '設置 ::節點 *' _ **與'T = ...'和'T = ...' _ ** –

+1

我懷疑這不是整個錯誤信息。 'q'的類型是什麼,'front'返回的是什麼? – molbdnilo

+0

也許'q'是一組指針指向const? –

回答

2

Queue類實例化一個Node<T>*類型已經......你再試圖返回一個指針到從您的Queue<T>::front方法中輸入T。如果您使用T=Node<T>*將您的Queue<T>類別即時更新,那麼您只需從front方法返回T類型,而不是T*。因此,改變你的front方法簽名如下:

template <typename T> 
class Queue 
... 
T front() 
{ 
    if (first != NULL) 
     return first->item; 
    else 
     return NULL; 
} 

現在,這可能會導致你一堆的問題,如果T不是一個指針類型......因此,你可能希望創建Queue<T>::front方法的情況下,專業化其中T已經是指針類型。例如:

//pointer-type specialization 
template<typename T> 
T Queue<T*>::front() 
{ 
    if (first != NULL) 
     return first->item; 
    else 
     return NULL; 
} 

//non-specialized version where T is not a pointer-type 
template<typename T> 
T* Queue<T>::front() 
{ 
    if (first != NULL) 
     return &(first->item); 
    else 
     return NULL; 
} 
+0

'front'應該可能返回一個*引用*到元素(與標準庫組件的'front'一致)。 –

+0

謝謝我仍然對模板不熟悉,我的隊列,堆棧和集合是我與他們學習的方式。 – LF4

+0

@DavidRodríguez-dribeas如果隊列是空的,會發生什麼?我明白用'std :: queue'假設你不能在空隊列上調用'front',但在這種情況下,他的'Queue'類被設置爲當隊列爲空時可以調用'front'。 – Jason

相關問題