我有这三个文件,main.cpp,DynamicArray.cpp,DynamicArray.h。在两个cpp文件中我都包含DynamicArray.h,我收到以下错误。
$ g++ main.cpp DynamicArray.cpp
/tmp/ccDGRYws.o: In function `testDynamicArray()':
main.cpp:(.text+0x11): undefined reference to `DynamicArray<int>::DynamicArray()'
main.cpp:(.text+0x1d): undefined reference to `DynamicArray<int>::DynamicArray()'
main.cpp:(.text+0x39): undefined reference to `DynamicArray<int>::~DynamicArray()'
main.cpp:(.text+0x5a): undefined reference to `DynamicArray<int>::add(int)'
main.cpp:(.text+0x72): undefined reference to `DynamicArray<int>::size()'
main.cpp:(.text+0xb8): undefined reference to `DynamicArray<int>::~DynamicArray()'
main.cpp:(.text+0xc9): undefined reference to `DynamicArray<int>::~DynamicArray()'
collect2: error: ld returned 1 exit status
当我将main.cpp中的DynamicArray.h更改为DynamicArray.cpp时,它可以正常工作。为什么不能使用.h?
的main.cpp
#include <iostream>
#include <assert.h>
#include "DynamicArray.h"
void testDynamicArray(){
DynamicArray<int> array1;
array1 = DynamicArray<int>();
int initialSize = 10;
for (int i = 0; i < initialSize; i++) {
array1.add(i);
}
assert(array1.size() == initialSize);
std::cout << "All tests for DynamicArray pass." << std::endl;
}
int main(){
testDynamicArray();
}
DynamicArray.cpp
#include "DynamicArray.h"
#include <iostream>
template <typename T>
DynamicArray<T>::DynamicArray(){
numElements = 0;
arraySize = 10;
theArray = new T[arraySize];
}
template <typename T>
DynamicArray<T>::~DynamicArray(){
delete[] theArray;
}
template <typename T>
int DynamicArray<T>::size(){
return numElements;
}
template <typename T>
bool DynamicArray<T>::isEmpty(){
return (numElements == 0);
}
template <typename T>
void DynamicArray<T>::increaseSize(){
T* tempArray = new T[arraySize * 2];
for(int i = 0; i <= numElements; i++) {
tempArray[i] = theArray[i];
}
delete[] theArray;
theArray = tempArray;
arraySize *= 2;
}
template <typename T>
void DynamicArray<T>::insert(T newElement, int index){
if (numElements == arraySize) {
increaseSize();
}
for (int i = numElements; i >= index ; i--) {
theArray[i] = theArray[i-1];
}
theArray[index] = newElement;
numElements++;
}
template <typename T>
void DynamicArray<T>::add(T newElement){
if(numElements == arraySize)
increaseSize();
theArray[numElements] = newElement;
numElements++;
}
template <typename T>
T DynamicArray<T>::get(int index){
return theArray[index];
}
template <typename T>
bool DynamicArray<T>::deleteIndex(int index){
if(index < 0 || index >= numElements)
return false;
for (int i = index; i < numElements-1; i++)
{
theArray[i] = theArray[i+1];
}
numElements--;
return true;
}
DynamicArray.h
#ifndef DYNAMICARRAY
#define DYNAMICARRAY
template <typename T>
class DynamicArray{
private:
T* theArray;
int numElements;
int arraySize;
void increaseSize();
public:
DynamicArray();
~DynamicArray();
int size();
bool isEmpty();
void insert(T newElement, int index);
void add(T newElement);
bool deleteIndex(int index);
T get(int index);
};
#endif