在本题中,CIntArray是一个整型数组的包装类;CIntArrayPtr聚合了一个CIntArray指针成员,并通过实现重载->操作符达到可以如操作指针一样操作CIntArray对象。本题的难点在于CIntArrayPtr的拷贝构造函数不能简单得对指针进行地址赋值,而必须同时进行内存拷贝;原因是如果不进行内存拷贝,则会出现多个CIntArrayPtr指向同一个CIntArray对象内存区的情况,这样当某个CIntArrayPtr对象析构后,如果其他CIntArrayPtr对象析构,则会出现对无效内存的释放错误。
#include "stdafx.h"
#include <iostream.h>
#include "memory.h"
class CIntArray
{
public:
friend class CIntArrayPtr;
CIntArray(int initSize = 50)
{
if (initSize <= 0)
m_iTotalSize = 50;
m_iTotalSize = initSize;
m_pArry = new int[m_iTotalSize];
}
~CIntArray()
{
delete[] m_pArry;
}
//implement operator [ ] to get and set the definite element
int& operator [](int index)
{
return m_pArry[index];
}
//implement a friend function operator << to output all elements in this array.
friend ostream& operator <<(ostream& os,CIntArray& intarray)
{
for(int i = 1; i <= intarray.m_iTotalSize; i++)
{
os << intarray[i - 1];
os << " ";
if(i%5 == 0)
{
os << endl;
}
}
return os;
}
private:
int *m_pArry;
int m_iTotalSize;
};
class CIntArrayPtr
{
public:
CIntArrayPtr(CIntArray* intArr, int curPos = 0)
{
m_pIntArray = intArr;
if (curPos >= 0 && curPos < intArr->m_iTotalSize)
m_iCurrentPos = curPos;
else
m_iCurrentPos = 0;
}
CIntArrayPtr(const CIntArrayPtr& ptr)
{
this->m_iCurrentPos = ptr.m_iCurrentPos;
this->m_pIntArray = new CIntArray(ptr.m_pIntArray->m_iTotalSize);
memcpy(m_pIntArray->m_pArry, ptr.m_pIntArray->m_pArry, this->m_pIntArray->m_iTotalSize * sizeof(int));
}
~CIntArrayPtr()
{
delete m_pIntArray;
m_pIntArray = NULL;
}
int& operator *()
{
return (*m_pIntArray)[m_iCurrentPos];
}
//implement operator ++ for the prefix version (e.g. ++spIntArray)
CIntArrayPtr& operator++()
{
m_iCurrentPos++;
return *this;
}
//implement operator ++ for the suffix version (e.g. spIntArray++)
CIntArrayPtr operator++(int)
{
CIntArrayPtr ptrTemp(*this);
m_iCurrentPos++;
return ptrTemp;
}
CIntArray* operator ->()
{
return m_pIntArray;
}
private:
CIntArray *m_pIntArray;
int m_iCurrentPos;
};
int main(int argc, char* argv[])
{
// create a int array and store it into the smart pointer
CIntArrayPtr spIntArray(new CIntArray(20), 0);
//set value to very element in this array
for (int i = 0; i < 20; i++)
{
*spIntArray = i;
spIntArray++;
}
return 0;
}

最新回复