2011-09-19 82 views
1

我已經定義了一個模板類,像這樣(提供.HPP文件):沒有調用模板類,C++

#ifndef PERSOANLVEC_H_ 
#define PERSOANLVEC_H_ 

#include <vector> 

using namespace std; 

template<class T, class PrnT> class PersoanlVec { 
public: 
    PersoanlVec(); 
    ~PersoanlVec(); 
    void push_back(T t); 
    void erase(int index); 
    PersoanlVec& operator[](int index); 
    const PersoanlVec& operator[](int index) const; 
    void print() const; 
    size_t size(); 
private: 
    vector<T> _vector; 
}; 

#endif /* PERSOANLVEC_H_ */ 

現在,一切都OK編譯這個類。當我嘗試使用它時,我得到 undefined reference to PersoanlVec<Person, Person>::PersoanlVec()'。 此處,我把它叫做:

#include "Person.h" 
#include "PersoanlVec.hpp" 
#include <cstdlib> 

int main(void) 
{ 
    Person p1("yotam"); 
    Person p2("yaara"); 
    PersoanlVec<Person,Person> *a = new PersoanlVec<Person,Person>(); //<---ERROR HERE 
    return EXIT_SUCCESS; 
} 

這是我第一次嘗試使用模板,它不是對我來說很清楚明顯。我有沒有參數的構造函數,任何想法? 謝謝!

+3

哇,我從來沒有見過這麼多*一致*拼寫錯誤。 – Puppy

+0

「PersoanlVec」的實現在哪裏? (順便說一句,是它打算是'PersonalVec'?) –

+0

@DeadMG:編碼助手有兩方面 –

回答

4

你有你的構造和功能於一身的.cpp文件中的內容?如果是,那就是你的問題。把它們在頭文件,可能只是內聯類本身:

template<class T, class PrnT> class PersoanlVec { 
public: 
    PersoanlVec(){ 
     // code here... 
    } 

    ~PersoanlVec(){ 
     // code here... 
    } 

    void push_back(T t){ 
     // code here... 
    } 

    void erase(int index){ 
     // code here... 
    } 

    PersoanlVec& operator[](int index){ 
     // code here... 
    } 

    const PersoanlVec& operator[](int index) const{ 
     // code here... 
    } 

    void print() const{ 
     // code here... 
    } 

    size_t size(){ 
     // code here... 
    } 

private: 
    vector<T> _vector; 
}; 

至於原因,看看here

0

我敢肯定你忘記了將文件添加到編輯過程。小心你的拼寫錯誤,因爲這會導致一般的疼痛。

只要你有不同的編譯單元(例如,每個類都帶有.h/.cpp的類),你的類需要知道接口,通常包含頭文件的原因,然而編譯器也需要知道這些實現,以便它可以將您的二進制文件綁定在一起。

因此,您將需要調用編譯器通過所有.cpp文件在您的項目給它,否則將無法讓你知道你正在引用未實現部分。

+0

雖然這是一個普通班的情況下,類模板不遵守這一規則。因此,請參閱w00te或我的回答。 – Xeo

0

你需要將所有的頭文件,而不是CPP文件中保存你的模板函數定義 - 這基本上是因爲模板定義將被多次使用,這取決於哪些參數你傳遞給它來創建多種類型作爲代碼的類型參數。應該在CPP文件中定義的唯一模板相關函數是模板特化函數 - 您希望明確說出的那些函數(如果用戶在類型A和B中傳遞,則專門執行此操作而不是默認操作)。