永发信息网

VC++课程设计

答案:1  悬赏:0  手机版
解决时间 2021-01-20 10:54
  • 提问者网友:容嬷嬷拿针来
  • 2021-01-20 05:51
VC++课程设计
最佳答案
  • 五星知识达人网友:封刀令
  • 2021-01-20 06:28
#include
using std::cout;
using std::endl;

template
class CTest
{
public:
CTest(int iCapacity = 1);
~CTest();
int Size() const; //当前元素个数
void PushBack(T t);
void Print() const;
int Capacity() const; //当前容量大小
void SetSize(int iCapacity); //设置容量大小
void RemoveAll(); //清空所有元素
private:
T *m_pData;
int m_iSize;
int m_iCapacity;
};

template
CTest::CTest(int iCapacity)
{
m_pData = new T[iCapacity];
m_iCapacity = iCapacity;
m_iSize = 0;
}

template
CTest::~CTest()
{
delete []m_pData;
m_pData = NULL;
m_iSize = m_iCapacity = 0;
}

template
CTest::Capacity() const
{
return m_iCapacity;
}

template
CTest::Size() const
{
return m_iSize;
}

template
void CTest::Print() const
{
for(int i=0; i {
cout < }
cout <}

template
void CTest::SetSize(int iCapacity)
{
if(iCapacity <= m_iCapacity)
{
return ;
}

int i = 0;
//申请空间保存原来数据
T *pTemp = new T[m_iCapacity];
for(i=0; i {
pTemp[i] = m_pData[i];
}

//将原来空间释放再申请iCapacity空间
delete []m_pData;

m_pData = new T[iCapacity];

for(i=0; i {
m_pData[i] = pTemp[i];
}

m_iCapacity = iCapacity;
delete []pTemp;
}

template
void CTest::RemoveAll()
{
//这个功能应该是清空当前数组中的所有元素,但空间还是保留着的。
m_iSize = 0;
}

template
void CTest::PushBack(T t)
{
int i = 0;
if(m_iSize == m_iCapacity)
{
//申请空间保存原来数据
T *pTemp = new T[m_iCapacity];
for(i=0; i {
pTemp[i] = m_pData[i];
}

//将原来空间释放再申请两倍空间
delete []m_pData;

m_pData = new T[m_iCapacity*2];

for(i=0; i {
m_pData[i] = pTemp[i];
}

m_iCapacity *= 2;
delete []pTemp;
}

//存放到后面
m_pData[m_iSize++] = t;
}

int main(int argc, char* argv[])
{
CTest test;
int i = 0;
for(i=0; i<10; i++)
{
test.PushBack(i);
}

cout<< test.Capacity() <<" " < test.Print();

cout <<"--------------------------\nSetSize:\n";
test.SetSize(20);
cout<< test.Capacity() <<" " < test.Print();

cout <<"--------------------------\nRemoveAll:\n";
test.RemoveAll();
cout<< test.Capacity() <<" " < test.Print();

cout <<"--------------------------\n";
for(i=10; i>0; i--)
{
test.PushBack(i);
}
cout<< test.Capacity() <<" " < test.Print();

return 0;
}
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯