好吧,我正在研究模板,但我对下一个代码有疑问:
#include <iostream>
using namespace std;
template<class T, int n>
class Table
{
public:
Table();
//~Table();
int& operator[](int i);
bool Resize(int n);
int Count();
void Free();
private:
T* inst;
int count;
};
template<class T, int n>
Table<T, n>::Table()
{
inst = new T[n];
count = n;
}
template<class T, int n>
void Table<T, n>::Free()
{
delete[] this->inst;
}
template<class T, int n>
int& Table<T, n>::operator[](int i)
{
return inst[i];
}
template<class T, int n>
bool Table<T, n>::Resize(int n)
{
this->inst = (T*)realloc(this->inst, sizeof(T)*count + sizeof(T)*n);
if(!inst)
return false;
return true;
}
template<class T, int n>
int Table<T, n>::Count()
{
return this->count;
}
template<typename T, int n> void ShowTable(Table<T, n> t)
{
for(int i=0; i<t.Count(); i++)
cout<<t[i]<<endl;
}
int main()
{
Table<int, 2> table;
table[0] = 23;
table[1] = 150;
ShowTable(table);
system("pause");
table.Free();
return 0;
}
它可以工作,但是当我将它放入delete[] this->inst;
析构函数时,它会抛出一个断言失败,我不知道为什么......我的意思是,删除析构函数中的资源是不是很糟糕?