读书人

帮忙看看模仿MFC中的CPlex类 写的有什

发布时间: 2012-03-28 15:40:03 作者: rapoo

帮忙看看模仿MFC中的CPlex类 写的有什么问题,或者说有什么不足的地方。-----新人
//.h
typedef unsigned int UINT;
typedef unsigned char BYTE;

#define NULL 0

#include <iostream>
#include <stdio.h>
class CPlex
{
public:
CPlex* m_pNext;
void* data()
{
return this + 1;
}
static CPlex* Create(CPlex*& pCPlex, UINT nMax, UINT cbElement);
void FreeDataChain();

};

//.cpp

#include "plex.h "

CPlex* CPlex::Create(CPlex*& pCPlex, UINT nMax, UINT cbElement)
{
//ASSERT(nMax > 0 && cbElement > 0);
if (nMax > 0 && cbElement > 0)
{
return NULL;
}
BYTE* pData = new BYTE[sizeof(CPlex) + nMax * cbElement];
memset(pData + sizeof(CPlex), 0, nMax * cbElement);
CPlex* pNewCplex = (CPlex*)pData;
pNewCplex-> m_pNext = pCPlex;
pCPlex = pNewCplex;
return pNewCplex;
}

void CPlex::FreeDataChain()
{
CPlex* p;
BYTE* bp;
for (p = this; p != NULL; p = p-> m_pNext)
{
bp = (BYTE*)p;
delete[] bp;
}
}

int main()
{
CPlex* p0 = NULL;
CPlex* p1= CPlex::Create(p0, 1000, sizeof(float));
//std::cout < < sizeof(CPlex) < < std::endl;
float* f = (float*)p1-> data();

p1-> FreeDataChain();


return 1;
}

[解决办法]
if (nMax > 0 && cbElement > 0)
{
return NULL;
}

应该是

if (nMax * cbElement <= 0)
{
return NULL;
}


这才是对错误参数的处理


还有

memset(pData + sizeof(CPlex), 0, nMax * cbElement);

如果可以省了就省了


读书人网 >C++

热点推荐