gpt4 book ai didi

c++ - 类模板的问题

转载 作者:行者123 更新时间:2023-11-30 02:08:18 24 4
gpt4 key购买 nike

我有作业要做,但我对类模板不是很熟悉。

任务是:

There's a major problem in the implementation of the following class. Can you spot it? How can you fix the problem? You can propose more than one solution, depending on the requirement specifications of the class.

    template <class T>
class Array
{
private:
T *m_pData;
unsigned int m_nSize;

public:
Array(unsigned int nSize) : m_nSize(nSize)
{
if(m_nSize > 0)
m_pData = new T[m_nSize];
}

virtual ~Array()
{
if(m_pData != NULL)
delete m_pData;
}
bool Set(unsigned int nPos, const T& Value)
{
if(nPos < m_nSize)
{
m_pData[nPos] = Value;
return true;
}
else
return false;
}

T Get(unsigned int nPos)
{
if(nPos < m_nSize)
return m_pData[nPos];
else
return T();
}
};

据我所知,存在内存泄漏。你发现其他问题了吗?提示比准确的答案更受欢迎;)

最佳答案

  1. 构造函数-当nSize为0时需要设置m_pData的值
  2. 您可以删除空指针,因此析构函数中不需要 if 语句。删除应该是delete[]

关于c++ - 类模板的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7067792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com