第14周项目3--数组类模板
来源:互联网 发布:mac photoshop 价格 编辑:程序博客网 时间:2024/05/05 00:53
代码:
/**Copyright (c) 2016, 烟台大学计算机与控制工程学院*All rights reserved.*文件名称:main.cpp;*作 者:岳成艳 2016年6月11号;*版 本 号:vc++6.0;**问题描述:数组类的模板。*程序输入:略;*程序输出:略;*/#include<iostream>#include<iomanip>#include<cassert>using namespace std;template<class T> //数组类模板定义class Array{private: T* list; //用于存放动态分配的数组内存首地址 int size; //数组大小(元素个数)public: Array(int sz=50); Array(const Array<T> &a); ~Array(); //析构函数 Array<T>&operator =(const Array<T> &m); //重载“=” T &operator [] (int i); //重载“【】” const T &operator [](int i) const; operator T *(); //重载到T*类型的转换 operator const T *()const; int getSize() const; //取数组的大小 void resize(int sz);//修改数组的大小};template <class T>Array<T>::Array(int sz) //构造函数{ assert(sz>0); size=sz; list=new T[size];}template <class T>Array<T>::~Array() //析构函数{ delete [] list;}template <class T>Array<T>::Array(const Array<T>&a) //复制构造函数{ size=a.size; list=new T[size]; for(int i=0;i<size;i++) list[i]=a.list[i];}template <class T>Array<T> &Array<T>::operator =(const Array<T>&m) //重载“=”{ if(m!=this) { if(size!=m.size) { delete [] list; size=m.size; list= new T[size]; } for(int i=0;i<size;i++) list[i]=m.list[i]; } return *this;}template <class T>T &Array<T>::operator[](int n){ assert(n>=0&&n<size); return list[n]; }template<class T>const T&Array<T>::operator[] (int n) const{ assert(n>=0&&n<size); //检查下标是否越界 return list[n];//返回下标为n的数组元素}template<class T>Array<T>::operator T*()//指针转换运算{ return list;}template<class T>Array<T>::operator const T*()const //指针转换运算符重载{ return list;}template <class T>int Array <T>::getSize() const //取当前数组的大小{ return size;}template<class T>void Array<T>::resize(int sz){ assert(sz>=0); if(sz==size) return ; T *newList=new T[sz]; int n=(sz<size)?sz:size; //重新分配小的内存空间 for(int i=0;i<size;i++) newList[i]=list[i]; delete [] list; list =newList; size=sz;}int main(){ Array<int> a(10); //用来存放质数的数组,初始状态有10个元素 int n,count=0; cout<<"Enter a value >=2 as upper limit for prime number:"; cin>>n; for(int i=2;i<=n;i++) { bool isPrime=true; for(int j=0;j<count;j++) if(i%a[j]==0) //若i被a[j]整除,说明I不是质数 { isPrime =false; break; } if(isPrime) { if(count==a.getSize()) a.resize(count * 2); a[count++]=i; } } for(int i=0;i<count;i++) cout<<setw(8)<<a[i]; cout << endl; return 0;}
运行测试:
0 0
- 第14周项目3-数组类模板
- 第14周项目3:数组类模板
- 第14周项目3--数组类模板
- 第14周项目3-数组类模板
- C++第14周项目模板【项目3-数组类模板】
- 第14周实践项目-数组类模板
- 第14周项目4-数组类模板
- 第14周项目 2—数组类模板
- 第14周项目三—数组类模板
- 第14周实践项目3——数组类模板
- C++第14周项目模板【项目2-两个成员的类模板】 !!!!!!!
- 第14周实践项目-两个成员的类模板
- 第14周项目-排序函数模板
- 第6周项目6-2,3复数模板类
- 第6周项目6-3复数模板类
- 第十四周项目 3 数组类模板
- 项目43--数组类模板
- 十四周项目-项目3-数组类模板
- 4K播出(下)
- Egret教程(二、HelloWorld)
- Android基本控件常用属性及方法
- Android编译系统环境初始化过程分析
- 面试:哈希:常数时间
- 第14周项目3--数组类模板
- SpringMVC学习系列(8) 之 国际化
- 关于python中的空格错误
- UEditor之基于Java图片上传前后端源码研究
- SpringMVC学习系列(7) 之 格式化显示
- 【GDOI2014模拟】网格
- 腾讯17年暑期实习生笔试题 - 字符移位
- 自学前端1
- Windows中Android Studio 中Git配置