C++ 数组类模板优化:内存管理和输入输出操作
#include
template
private: T *m_arr; int m_size;
public: Array(int size) : m_size(size) { m_arr = new T[size]; memset(m_arr, 0, sizeof(T) * size); } ~Array() { delete[] m_arr; }
T &operator[](int index)
{
return this->m_arr[index];
}
int size()
{
return m_size;
}
};
template
template
int main()
{
Array
cin >> Aa;
cout << Aa << endl;
}
修改内容:
- 在构造函数中,将 memset 函数的第三个参数修改为
sizeof(T) * size,以正确计算需要初始化的字节数。 - 在析构函数中,将 delete 修改为 delete[],以正确释放数组内存。
- 在运算符重载
>>的实现中,将输入流对象的类型由<<改为>>。 - 将
Array<T1> &ra改为Array<T> &ra,以避免类型不匹配的错误。
原文地址: https://www.cveoy.top/t/topic/b2wA 著作权归作者所有。请勿转载和采集!