C++类模板(二)用类模板实现可变长数组
生活随笔
收集整理的這篇文章主要介紹了
C++类模板(二)用类模板实现可变长数组
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
#include <iostream>
#include <cstring>
using namespace std;
template <class T> class CArray{int size ; //數(shù)組元素的個數(shù)T *ptr;public:CArray(int s=0);//數(shù)組元素的個數(shù)CArray(CArray &a);~CArray();void push_back(const T&V) ;//用于在數(shù)組隊尾添加一個元素vCArray &operator=(const CArray &a);//用于數(shù)組對象間賦值T length() {return size;}T &operator[] (int i){//用以支持根據(jù)下標訪問數(shù)組元素,如a[i]=4,和n=a[i]這樣的語句return ptr[i];}
};template <class T>CArray<T>::CArray(int s ):size(s) {if (s==0)ptr=NULL;elseptr =new T[s];
}template <class T>
CArray<T>::CArray(CArray &a) {if (!a.ptr){ptr=NULL;size=0;return ;}ptr=new T[a.size];memcpy(ptr,a.ptr ,sizeof (T) *a.size);size=a.size;
}template <class T>CArray<T>::~CArray(){if (ptr) delete [] ptr ;
}template <class T>
CArray<T> &CArray<T>::operator=(const CArray &a) {//賦值號的作用是使"="左邊對象里存放的數(shù)組,大小和內(nèi)容都和右邊的對象一樣if (this ==&a) //防止a=a這樣的賦值導(dǎo)致出錯return * this ;if (a.ptr==NULL){ //如果a 里面的數(shù)組是空的if (ptr)delete [] ptr ;ptr=NULL;size=0;return *this ;}if (size<a.size) {if (ptr)delete[] ptr;ptr = new T[a.size];}memcpy(ptr ,a.ptr ,sizeof(T)*a.size);size=a.size;return *this;}
template <class T>
void CArray<T>::push_back(const T&v)
{//在數(shù)組尾部添加一個元素if (ptr){T *tmpPtr =new T[size+1];//重新分配空間memcpy(tmpPtr,ptr,sizeof (T) *size);delete[] ptr;ptr=tmpPtr;}else //數(shù)組本來是空的ptr= new T[1];ptr[size++] =v;//加入新的數(shù)組}int main()
{CArray<int >a ;for (int i =0 ;i<5;++i)a.push_back(i);for (int i=0;i<a.length();++i)cout <<a[i]<<" ";return 0;
}
0 1 2 3 4
《新程序員》:云原生和全面數(shù)字化實踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀
總結(jié)
以上是生活随笔為你收集整理的C++类模板(二)用类模板实现可变长数组的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++类模板(一)
- 下一篇: C++重载下标操作符[](二)