2017-07-18 108 views
0

我有一個模板類,它接受2種數據類型T1和T2,它應該佔用2種不同的數據類型,然後使用方法顯示將它們打印到終端()C++具有多種數據類型的'Undefined Reference'模板類

pair.h

#ifndef PAIR_H 
#define PAIR_H 

template <class T1, class T2> 
class Pair 
{ 
public: 
    Pair(); 
    Pair(const T1 & t1, const T2 & t2) : first(t1), second(t2) {} 
    ~Pair(); 

    T1 getFirst() const {return first;} 
    T2 getSecond() const {return second;} 
    void setFirst(const T1 & t1) {this->first = t1;} 
    void setSecond(const T2 & t2) {this->second = t2;} 
    void display() 
    { 
     std::cout << first << " - " << second << endl; 
    } 


private: 
    T1 first; 
    T2 second; 
}; 

#endif // PAIR_H 

該類在頭文件 「pair.h」,沒有cpp文件定義。當我嘗試創建Pair類的新對象我得到的錯誤:

Undefined reference to 'Pair<string, string>::Pair()' 
Undefined reference to 'Pair<int, int>::Pair()' 
Undefined reference to 'Pair<string, int>::Pair()' 
Undefined reference to 'Pair<string, string>::~Pair()' 
Undefined reference to 'Pair<int, int>::~Pair()' 
Undefined reference to 'Pair<string, int>::~Pair()' 

當我調用類我把它的main()函數就像

main.cpp

#include <iostream> 
#include <string> 
using namespace std; 

#include "pair.h" 

int main() 
{ 
... 
    Pair<string, string> fullName; 
    fullName.setFirst(first); 
    fullName.setSecond(last); 
    fullName.display(); 
    ... 
    Pair<int, int> numbers; 
    numbers.setFirst(num1); 
    numbers.setSecond(num2); 
    numbers.display(); 
    ... 
    Pair<string, int> grade; 
    grade.setFirst(name); 
    grade.setSecond(score); 
    grade.display(); 
... 
} 
的默認構造函數

The makefile:

a.out : check11b.cpp pair.h 
    g++ check11b.cpp 

由於這是學校的作業,唯一的規則是在makefile文件main.cpp文件無法更改。 請幫忙嗎?

+1

@MajidAbdolshah這是完全錯誤的,如果您的頭文件包含所有實現,則不需要單獨的「.cpp」文件。和模板必須在頭文件中完全實現,你不能將實現移動到一個單獨的文件 – UnholySheep

+0

@UnholySheep當然,你是對的。我看到了這個:https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file –

回答

3

我有這樣的錯誤消息,我所需要做的只是改變默認構造函數和析構函數的定義,因爲只有一個定義,並沒有實際的實現。將默認構造函數更改爲這個。

Pair() {} 

相同的析構函數。