原创:
C++ 简单实现数组类泛型编程示例
1、使用模板来实现泛型编程
2、本数组应该能够存储各种基础类型,各种复杂的类类型
3、应该实现部分操作符重载
其实操作符重载满满的都是套路。
代码如下:
-
模板类实现:
-
/*************************************************************************
-
> File Name: arra.cpp
-
> Author: gaopeng QQ:22389860 all right reserved
-
> Mail: gaopp_200217@163.com
-
> Created Time: Mon 10 Apr 2017 08:28:01 AM CST
-
************************************************************************/
-
-
#include<iostream>
-
#include <stdlib.h>
-
#include <string.h>
-
using namespace std;
-
-
-
template <typename T>
-
class myarray
-
{
-
private:
-
T* array;
-
unsigned int lenth;
-
public:
-
myarray();
-
myarray(unsigned int len);
-
myarray(const myarray& a);
-
myarray& operator=(const myarray& b);
-
T& operator[](int ind);
-
~myarray();
-
};
-
-
-
-
-
template <typename T>
-
myarray<T>::~myarray()
-
{
-
if(this->array != NULL)
-
{
-
delete [] this->array;
-
this->array = NULL;
-
}
-
-
}
-
-
-
template <typename T>
-
myarray<T>::myarray()
-
{
-
this->array = NULL;
-
this->lenth = 0;
-
}
-
-
template <typename T>
-
myarray<T>::myarray(unsigned int len)
-
{
-
this->array = new T[len];
-
this->lenth = len;
-
memset(this->array,0,sizeof(T)*len);
-
}
-
template <typename T>
-
myarray<T>::myarray(const myarray<T>& a)
-
{
-
int i;
-
this->lenth = a.lenth;
-
this->array = new T[a.lenth];
-
memset(this->array,0,sizeof(T)*a.lenth);
-
for(i=0;i<a.lenth;i++)
-
{
-
*(this->array+i) = *(a.array+i);
-
}
-
}
-
-
template <typename T>
-
myarray<T>& myarray<T>::operator=(const myarray<T>& a)
-
{
-
if(this->array != NULL)
-
{
-
delete [] this->array;//调用类的析构函数不能用free
-
this->array = NULL;
-
}
-
this->array = new T[a.lenth];
-
this->lenth = a.lenth;
-
-
for(int i=0;i<a.lenth;i++)
-
{
-
*(this->array+i) = *(a.array+i);//元素对象复制调用对象的=操作符重载
-
}
-
-
return *this;
-
}
-
-
template <typename T>
-
T& myarray<T>::operator[](int ind)
-
{
-
if(ind>=this->lenth)
-
{
-
exit(10);
-
}
-
return *(this->array+ind);
-
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/7728585/viewspace-2136044/
,如需转载,请注明出处,否则将追究法律责任。