main.c
#include <stdio.h> #include <string.h> #include "Array.h" int main() { Array<int> a; // 长度可变的数组 a.PushBack(1); a.PushBack(2); a.PushBack(3); a.PushBack(4); a.PushBack(5); int size = a.Size(); Array<float> b; b.PushBack(2.3f); return 0; }
Aarry.h
#ifndef _ARRAY_H #define _ARRAY_H // 用于存放double类型的对象 template <typename _TT> class Array { public: Array(int capacity=4) { m_buffer = new _TT[capacity]; m_capacity = capacity; m_size = 0; } void PushBack(_TT val) { if(m_size >= m_capacity) { Resize(); } m_buffer[m_size] = val; m_size ++; } int Capacity() { return m_capacity; } int Size() { return m_size; } private: void Resize() { // 创建一个更大的缓冲区 int n = m_capacity + 4; _TT* buf = new _TT[n]; // 拷贝原有的内容 memcpy(buf, m_buffer, m_capacity * sizeof(_TT) ); // 删除旧的内容,释放其内存 delete [] m_buffer; // 更新一下成员变量 m_capacity = n; m_buffer = buf; } private: _TT* m_buffer; int m_capacity; // 容量 int m_size; // 已经存放的对象的个数 }; #endif