我正在尝试编译一个使模板实例化的函数,但我没有运气,并且通过debug显示的错误告诉我: 未定义对`DynamicArray :: DynamicArray(unsigned int)的引用 我已经尝试过在平台上找到的许多解决方案,但仍然无法弄清代码中的问题
-1- Main.cpp文件:
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
#include "DynamicArray.h"
using namespace std;
int main()
{
cout << "**** Testing the Dynamic Array ****" << endl << endl;
TestOne();
return 0;
}
-2- DynamicArray.h文件:
template<typename T>
class DynamicArray
{
public:
//DynamicArray();
DynamicArray(unsigned int ssize);
void initialize(unsigned int );
void expand();
void Add(const T& );
void Resize(int );
const int& GetCapacity()const { return 18 ; }
const int& GetSize()const { return this->nOfEl;}
T& operator[] (const int index);
virtual ~DynamicArray();
protected:
private:
int cap;
int nOfEl;
T **arr;
};
-3- DynamicArray.cpp文件:
#include "DynamicArray.h"
#include <cstddef>
template<typename T>
DynamicArray<T>::DynamicArray(unsigned int ssize)
{
this->cap = 5;
this->nOfEl = 0;
this->arr = new T*[this->cap];
initialize();
}
template<typename T>
DynamicArray<T>::~DynamicArray()
{
for(size_t i=0; i < nOfEl ; i++)
{
delete this->arr[i];
}
delete[]this->arr;
}
template<typename T>
void DynamicArray<T>::initialize(unsigned int from)
{
for(size_t i = from ; i<cap ; i++)
{
this->arr[i] = nullptr;
}
}
template<typename T>
void DynamicArray<T>::expand()
{
this.cap *= 2;
T **tempArr = new T*[this.cap];
for(size_t i = 0 ; i < this.nOfEl ; i++)
{
tempArr[i] = new T(this->arr[i]);
}
for(size_t i=0; i < nOfEl ; i++)
{
delete this->arr[i];
}
delete[]this->arr;
this->arr = tempArr;
initialize();
}
template<typename T>
void DynamicArray<T>::Add(const T& element)
{
if(this->nOfEl >= this.cap)
{
this.expand();
}
this->arr[this->nOfEl++] = new T(element);
}
template<typename T>
void DynamicArray<T>::Resize(int newsize)
{
T **tempArr = new T*[newsize];
for(size_t i = 0 ; i < newsize ; i++)
{
tempArr[i] = new T(this->arr[i]);
}
newsize++;
for(size_t i=newsize; i < nOfEl ; i++)
{
delete this->arr[i];
}
delete[]this->arr;
this->arr = tempArr;
initialize(newsize);
}