模板类,通用类型名与非类型参数
来源:互联网 发布:勇士vs活塞数据10.30 编辑:程序博客网 时间:2024/06/05 06:05
C++中有一系列用来存储和修改变量的类,用来实现栈和队列等数据结构,但若是每次遇到一种变量类型就要重写一个存储该类型的stack类未免太麻烦,为了解决这个问题,就需要使用模板类。
例:用模板类实现的一个简单stack类
template <class Type>class Stack{private: Type items[10]; int top;public: Stack(); bool push(const Type& item); bool pop(const Type& item); bool isfull();};template<class Type>Stack<Type>::Stack(){ top=-1;}template<class Type>bool Stack<Type>::push(const Type& item){ if(top<9){ items[++top]=item; return true; } else{return false;}}template<class Type>bool Stack<Type>::pop(const Type& item){ if(top>0){ item=items[top--]; return true; } else{return false;}}template<class Type>bool Stack<Type>::isfull(){ if(top==9)return true; else return false;}
若要声明一个栈实例,语法如下:
Stack<int> intstack;
Stack<double> doublestack;
Stack<string> stringstack;
模板类还能用于动态定义数组长度,用模板参数来提供常规数组的大小,举例如下:
template<class Type,int n> //n为一个非类型参数,或称为表达式参数class Stack{private: Type items[n]; int top;public: bool isfull; bool push(const Type& item); bool pop(const Type& item);};......
若要声明一个栈实例,语法如下:
Stack<int,10> intstack;
Stack<double,20> doublestack;
非类型参数还有一些限制,总结如下:
①非类型参数只能为整型,枚举类型,引用或指针。因此template<class Type,double n>是不合法的,但template<class Type,double *p>是合法的。
②模板代码中不能修改非类型参数的值,也不能使用其地址,所以n++,&n等操作是不合法的。这也造成了模板类创建数组的一大缺点,数组创建后无法动态改变大小。
阅读全文
0 0
- 模板类,通用类型名与非类型参数
- 非类型模板参数与 非类型类模板参数的使用
- 非类型模板类参数
- 模板非类型参数
- 非类型模板参数
- 非类型模板参数
- 非类型模板参数
- 非类型模板参数
- 非类型模板参数
- 非类型的模板参数
- 非类型函数模板参数
- 模板之非类型模板参数
- 模板笔记003 - 非类型模板参数
- class 与 typename (在模板定义上)的通用与各自特殊性(前者-类,后者-嵌套依赖类型名)
- C++ 类模板与无类型参数
- Nontype Class Template Parameters(非类型类模板参数)
- 模板类中的表达式(非类型)参数
- C++ Templates:非类型模板参数
- Python网络爬虫与信息提取-Day6-Beautiful Soup库
- 函数 mutex_init() / mutex_lock() / mutex_unlock()
- 欢迎使用CSDN-markdown编辑器
- Java基础(八)字符串与正则表达式
- 用微信小程序开店之九——小程序组件5:“表单”(3)
- 模板类,通用类型名与非类型参数
- secureCRT同时向多个打开的seesion发送命令
- 禅道的进阶使用
- Cookie是什么
- 常用排序算法总结(一)
- 详谈php静态方法及普通方法的区别
- [翻译] C# 8.0 预览
- 八种基本数据类型及封装类 与 一些基本数据类型的类封装(包装类)
- 美国学者:中国正处在失去中国固有传统的危险中