请大家说说我这个类的设计上有什么问题
- C/C++ code
/*用来批量存储文件头信息的类*/class CFHeaderData{private: void** Data; int CurIndex; int MaxIndex;public: CFHeaderData(const int MaxIndex); bool AddTag(const int TagVal,const char* TagName); void* GetData();};inline CFHeaderData::CFHeaderData(const int MaxIndex){ this->MaxIndex=MaxIndex; this->CurIndex=0; Data=new void*[MaxIndex];}inline bool CFHeaderData::AddTag(const int TagVal,const char* TagName){ if((MaxIndex-CurIndex)<3) return false; //空间不足,返回假 this->Data[CurIndex]=new int(TagVal); CurIndex++; this->Data[CurIndex]=new char(*TagName); CurIndex+=2; return true;}inline void* CFHeaderData::GetData(){ return Data;}
1.effective c++中的大师告诉我,尽量地使用const,但我看不出有什么用
2.由于这个数据是不需要频繁的插入和删除的,我没有使用链表,而是使用动态数组,由用户在调用构造函数时决定文件头信息的条目个数。
[解决办法]
挺好的!
[解决办法]
1. 没有析构函数,copy构造函数
2. this->Data[CurIndex]=new char(*TagName);这样赋值,Data[CurIndex]的指针指向的应该是一个字符而不是字符串,最后CurIndex+=2;为什么是加2?没明白。。。
3. 为什么GetData()返回的是void* 不是void**, GetData()函数后可以加上const
4. 这个类是要做什么的,弄的有点复杂,不能设计成模板类吗?
[解决办法]
1. 类型不安全
- C/C++ code
void**
[解决办法]
[解决办法]
[解决办法]
[解决办法]
给你一个用template的例子
- C/C++ code
#include <iostream>#include <string>#include <vector>using namespace std;template <class type>class CHeadData{ public: //CHeadData(); CHeadData(int val, const string &name, const type &reserved) { this->val = val; this->name = name; this->reserved = reserved; //"type" need to override = operator } CHeadData(const CHeadData &data) { this->value = data.value; this->name = data.name; this->reserved = data.reserved; } ~CHeadData(){} int GetVal() const {return this->val;} const string& GetName() const {return this->name; } const type& GetReserved() const {return this->reserved;} private: int val; string name; type reserved;};int main(){ vector< CHeadData<string>* > data; CHeadData<string> *test = new CHeadData<string>(1, "test", "test"); data.push_back(test);}