2011-12-26 223 views
1

我剛剛開始使用C++,並遇到了這個問題。我在Fifo.h定義的類先進先出:C++未定義的構造函數

/* Fifo.h */ 
#ifndef FIFO_H_ 
#define FIFO_H_ 

#include <atomic> 
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 

template <class T> 
class Fifo 
{ 
public: 

    Fifo<T>(int len); 
    ~Fifo<T>(); 

    int AddTokens(T* buffer, int len); 
    int RetrieveTokens(T* buffer, int len); 

private: 
    //int len; 

}; 

#endif /* FIFO_H_ */ 

而且在Fifo.cpp的定義:

/* Fifo.cpp*/ 
#include "Fifo.h" 

template <class T> 
Fifo<T>::Fifo(int len) 
{ 
    //_fifoptr = new FifoImpl_class((T)len); 
    printf ("From the constructor\n"); 
    //thisbuffer = malloc(sizeof(T)*len); 
} 


template <class T> 
Fifo<T>::~Fifo() { } 

template <class T> 
int Fifo<T>::AddTokens(T* buffer, int len) 
{ 
    printf("Added tokens\n"); 
    return(1); 
} 


template <class T> 
int Fifo<T>::RetrieveTokens(T* buffer, int len) 
{ 
    printf("Removed tokens\n"); 
    return(2); 
} 

而且,我測試我的課像這樣(Fifotest.cpp):

#include "Fifo.h" 
int main(int argc, char *argv[]) 
{ 
    Fifo<int> MyFifo(20); 
} 

用gcc-4.5構建它給了我這個錯誤: 未定義參考Fifo<int>::~Fifo()' undefined reference to先進先出:: FIFO(INT)」

看起來像我有相關的方法定義,但我無法弄清楚爲什麼我得到這個錯誤。我花時間搜索它,而選擇是跑上課並修改它。但是,我想知道我已經有什麼問題。將不勝感激任何幫助!

+2

這必須有六萬億投資。 – Puppy 2011-12-26 13:00:32

回答

2

If you put template definition in cpp file, the definitions will not be available outside that cpp file. 當你包括Fifotest.cppFifo.h,編譯器看到模板類的聲明,但它不看的方法的實現。將它們移動到Fifo.h標題後,應該編譯所有內容。

+0

嗯,你可以。你可以放任何你喜歡的任何地方。 C++不給猴子你的文件擴展名是什麼。當您使用傳統的包含方式時,它在大多數情況下只會導致錯誤。 – 2011-12-26 13:01:04

+0

我想你錯過了我的觀點。有很多情況下,它會工作得很好。您在「cpp文件」中編寫定義不是關鍵問題;該定義對其他TU是不可見的。因果關係,是的,但不等同! – 2011-12-26 13:05:25

2

2點:

  • 構造被錯誤地宣告。

    Fifo<T>(int len); //wrong 
    Fifo(int len); //right 
    
  • 模板應當以相同的翻譯單元在它們被使用來定義,所以具有獨立的h和cpp文件通常不爲模板工作(參見,例如,this question)。請將你的cpp文件的內容移動到頭文件中,你應該沒問題。

+0

其實,我很確定他們都是正確的 - Fifo '和Fifo'。但我可能是錯的。 – Puppy 2011-12-26 13:03:41

+1

我也是。在這種情況下,「Fifo」是「Fifo 」的同義詞,並且沒有聲明模板。但我也沒有嘗試。 – 2011-12-26 13:04:28

+0

@Tomalak:好的,Fifo確實是Fifo的代名詞,但它是一個注入類名,意味着它就像基類的公共成員一樣。所以我傾向於相信你不能聲明這樣的構造函數(我可能是錯的) – 2011-12-26 13:06:23

0

您應該在頭文件中提供定義。標準中存在export關鍵字,但通常的編譯器尚未實現它。

+0

實際上它已被刪除。 – 2011-12-26 13:02:13