模板类的定义与实现
来源:互联网 发布:始作俑者其乎后的意思 编辑:程序博客网 时间:2024/05/22 17:29
#ifndef ARRAY_H_INCLUDED
#define ARRAY_H_INCLUDED
#include <stddef.h>
template <typename T>
class Array{
public:
// Create an array with a default size that will grow as needed
Array();
virtual ~Array();
// Disallow assignment and pass-by-value
//Array<T>& operator=(const Array<T>& rhs) = delete;
//Array(const Array<T>& src) = delete;
// Return the value at index x. If index x does not exist in the array
// throw an exception of type out_of_range.
T getElementAt(size_t x) const;
// Sets the value at index x to val. If index is out of range,
// allocates more space to make it in range
void setElementAt(size_t x,const T& val);
private:
static const size_t kAllocSize = 4;
void Resize(size_t newsize);
// Sets all elements to 0
void initializeElements();
T* mElems;
size_t mSize;
};
template<typename T>
Array<T>::Array()
{
mSize = kAllocSize;
mElems = new T[mSize];
initializeElements();
}
template<typename T>
Array<T>::~Array()
{
delete [] mElems;
mElems = nullptr;
}
template<typename T>
T Array<T>::getElementAt(size_t x) const
{
if(x >= mSize)
throw std::out_of_range("");
return mElems[x];
}
template<typename T>
void Array<T>::setElementAt(size_t x,const T& val)
{
if(x >= mSize)
Resize(x + kAllocSize);
mElems[x] = val;
}
template<typename T>
void Array<T>::Resize(size_t newsize)
{
// Make a copy of the current elements pointer and size
T* oldElems = mElems;
size_t oldSize = mSize;
// Create new bigger array
mElems = new T[newsize];
initializeElements();
mSize = newsize;
for(size_t i = 0; i < oldSize; ++i)
mElems[i] = oldElems[i];
delete []oldElems;
oldElems = nullptr;
}
template<typename T>
void Array<T>::initializeElements()
{
for(size_t i = 0; i < mSize; ++i)
mElems[i] = T();
}
#endif // ARRAY_H_INCLUDED
0 0
- 模板类的定义与实现
- 模板类的定义和实现
- 模板类的定义与声明
- c++类模板的声明与定义
- 类模板成员函数的定义、实现分离与error LNK2019的解决办法
- C++类模板定义与实现的分离—学习C++数据抽象和问题求解
- VS 2013 C++ 类模板定义与实现 进行分离
- 模板的声明与定义
- 类的定义与实现
- 模板类定义与声明
- 模板类定义时,模板方法定义与声明的分离
- C++ 模板类的声明与定义
- c++模板类/函数的申明与定义
- 模板类中friend函数的声明与定义
- c++模板的定义和实现
- 模板类中友元函数的声明与定义
- 类的定义与成员实现
- String类的定义与实现
- reload()和replace()方法
- 『算法』Dinic求最大流
- PAT L1-020. 帅到没朋友
- ArrayList和LinkedList的区别
- 在O(1)时间复杂度删除链表节点
- 模板类的定义与实现
- 目标检测领域
- java之网络编程学习笔记
- JAVA面试题05-ConcurrentHashMap的实现
- MUI 混合开发 轮播图应用
- 第四周linux常用命令
- SublimeText 相关
- 用冒泡排序模拟实现qsort
- 回归故乡发展