首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请大家说说小弟我这个类的设计下有什么有关问题

2012-10-29 
请大家说说我这个类的设计上有什么问题C/C++ code/*用来批量存储文件头信息的类*/class CFHeaderData{priv

请大家说说我这个类的设计上有什么问题

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**
[解决办法]
探讨

引用:

1. 没有析构函数,copy构造函数

2. this->Data[CurIndex]=new char(*TagName);这样赋值,Data[CurIndex]的指针指向的应该是一个字符而不是字符串,最后CurIndex+=2;为什么是加2?没明白。。。

3. 为什么GetData()返回的是void* 不是void**, GetData()函数后可……

[解决办法]
探讨
引用:

1. 类型不安全 C/C++ code
void**

2. 在构造函数中动态分配资源(内存),请正确实现析构函数,复制拷贝,拷贝构造等
3. 封装被破坏了.
C/C++ code
void* GetData();


4. effective C++中原则根据需要使用。


谢谢,但是我不明白,这里的拷贝构造是必须的吗?为什么?

[解决办法]
探讨

1. 没有析构函数,copy构造函数

2. this->Data[CurIndex]=new char(*TagName);这样赋值,Data[CurIndex]的指针指向的应该是一个字符而不是字符串,最后CurIndex+=2;为什么是加2?没明白。。。

3. 为什么GetData()返回的是void* 不是void**, GetData()函数后可以加上const

4. 这……

[解决办法]
给你一个用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);} 

热点排行