2014-11-22 93 views
1

我想在C++中做一個簡單的邊界檢查數組。我已經在頭文件中聲明瞭一個類,並在一個單獨的源文件中定義了這個類。編譯步驟運行正常,但是當我嘗試將對象鏈接,我得到以下錯誤:未定義的參考錯誤在C++鏈接步驟

$ g++.exe -o a.exe src\main.o src\array.o 
src\main.o: In function `main': 
../src/main.cpp:7: undefined reference to `Array<int>::Array(int)' 
../src/main.cpp:9: undefined reference to `Array<int>::operator[](int)' 
../src/main.cpp:10: undefined reference t o `Array<int>::operator[](int)' 
../src/main.cpp:11: undefined reference t o `Array<int>::operator[](int)' 
../src/main.cpp:13: undefined reference t o `Array<int>::operator[](int)' 
../src/main.cpp:7: undefined reference to `Array<int>::~Array()' 
../src/main.cpp:7: undefined reference to `Array<int>::~Array()' 
collect2.exe: error: ld returned 1 exit status 

的main.cpp

#include <iostream> 
#include "array.hpp" 

using namespace std; 

int main() { 
    Array<int> x(10); // compiler error 

    x[0] = 1; // compiler error 
    x[1] = 2; // compiler error 
    x[2] = 3; // compiler error 

    cout << x[1] << endl; // compiler error 

    return 0; 
} 

array.hpp

#ifndef ARRAY_HPP_ 
#define ARRAY_HPP_ 

template <class T> 
class Array{ 
private: 
    T* array; 
    int length_; 
public: 
    Array(int); 
    ~Array(); 
    int Length(); 
    int& operator[](int); 
}; 

#endif /* ARRAY_HPP_ */ 

陣列。 cpp

#include "array.hpp" 

template <class T> 
Array<T>::Array(int size) { 
    length_ = size; 
    array = new T[size]; 
} 

template <class T> 
Array<T>::~Array() { 
    delete[] array; 
} 

template <class T> 
int Array<T>::Length() { 
    return length_; 
} 

template <class T> 
int& Array<T>::operator[](const int index) { 
    if (index < 0 || index >= length_) { 
    throw 100; 
    } 
    return array[index]; 
} 

回答

1

members of a templa te類應該在模板類自己定義的相同頭文件中。

1

模板類必須在頭文件中包含所有代碼,或者它們只能用於在cpp文件中顯式實例化的類型。