| //MyTable.h #ifndef MYTABLE_DEFINED #define MYTABLE_DEFINED #define MAX_ROW_COUNT 1024//设置这个宏是为了控制表的大小 #define MAX_COLUMN_COUNT 1024//别一不留神耗光了内存^_^ #include<string> using namespace std; template<class T> class MyTable { public: //构造函数和析构函数 MyTable(); MyTable(int RowCount,int ColumnCount); ~MyTable(); //功能函数 bool InitTable(int RowCount,int ColumnCount); bool SetValue(int Row,int Column,const T &Value); bool GetValue(int Row,int Column,T &Value) const; bool DeleteValue(int Row,int Column); void SetColumnName(int ColumnIndex,const string &Value); string GetColumnName(int ColumnIndex); bool IsInit(); int GetRowCount(); int GetColumnCount(); private: //私有数据成员 int RowCount; int ColumnCount; string *ColumnName; T **pData; bool isInit; }; //类模板实现 //构造函数和析构函数 template<class T> MyTable<T>::MyTable() { RowCount = 0; ColumnCount = 0; ColumnName = NULL; pData = NULL; isInit = false; } template<class T> MyTable<T>::MyTable(int RowCount,int ColumnCount) { this->RowCount = RowCount; this->ColumnCount = ColumnCount; ColumnName = new string[ColumnCount]; pData = new T * [RowCount * ColumnCount]; isInit = true; for(int i=0; i < ColumnCount; i++) { ColumnName[i] = ""; } for(int i=0; i < RowCount * ColumnCount; i++) { pData[i] = NULL; } } template<class T> MyTable<T>::~MyTable() { for(int i=0; i < RowCount*ColumnCount; i++) { delete pData[i]; } delete[] ColumnName; delete[] pData; } //功能函数 template<class T> bool MyTable<T>::InitTable(int RowCount,int ColumnCount) { if(isInit == true) return false; this->RowCount = RowCount; this->ColumnCount = ColumnCount; ColumnName = new string[ColumnCount]; pData = new T * [RowCount * ColumnCount]; isInit = true; for(int i=0; i < ColumnCount; i++) { ColumnName[i] = ""; } for(int i=0; i < RowCount * ColumnCount; i++) { pData[i] = NULL; } } template<class T> bool MyTable<T>::SetValue(int Row,int Column,const T &Value) { int i = Row * ColumnCount + Column; if(i> RowCount * ColumnCount || pData == NULL) return false; if(pData[i] != NULL) { delete pData[i]; } pData[i] = new T(Value); if(pData[i] == NULL) return false; else return true; } template<class T> bool MyTable<T>::GetValue(int Row,int Column,T &Value) const { int i = Row * ColumnCount + Column; if(i> RowCount * ColumnCount || pData == NULL) return false; Value = *pData[i]; return true; } template<class T> bool MyTable<T>::DeleteValue(int Row,int Column) { int i = Row * ColumnCount + Column; if(i> RowCount * ColumnCount || pData == NULL) return false; if(pData[i] != NULL) { delete pData[i]; } return true; } template<class T> void MyTable<T>::SetColumnName(int ColumnIndex,const string &Value) { ColumnName[ColumnIndex] = Value; } template<class T> string MyTable<T>::GetColumnName(int ColumnIndex) { return ColumnName[ColumnIndex]; } template<class T> int MyTable<T>::GetRowCount() { return RowCount; } template<class T> int MyTable<T>::GetColumnCount() { return ColumnCount; } template<class T> bool MyTable<T>::IsInit() { return isInit; } #endif |