前言
"打牢基础,万事不愁" .C++的基础语法的学习
引入
类模板是泛型编程的重要组成部分,通常用来实现数据结构,做成容器类.从几个现成容器探寻类模板定义的内容.引用了参考书<C++ Prime Plus> 6th Edition(以下称"本书")的几个例子:数组栈,指针栈,链队列
类模板回顾
类模板把数据类型---class类型或基本类型作为参数传入,设类型为T,则可以把T*(指针),T**(双重指针), T a[](数组)作为类模板属性.(自用)关于程序的一些概念4:C++泛型初探-优快云博客
类模板的类名和普通class类相同,构造函数形式和普通class类也相同.在类模板对象使用时,要类名后加上"<具体类型名>",在定义类模板方法时,要在类名后加上"<形参类型名>"
数组栈
本书P569,复制书中stacktp.h代码如下:
// stacktp.h -- a stack template
#ifndef STACKTP_H_
#define STACKTP_H_
template <class Type>
class Stack
{
private:
enum {MAX = 10}; // constant specific to class
Type items[MAX]; // holds stack items
int top; // index for top stack item
public:
Stack();
bool isempty();
bool isfull();
bool push(const Type & item); // add item to stack
bool pop(Type & item); // pop top into item
};
template <class Type>
Stack<Type>::Stack()
{
top = 0;
}
template <class Type>
bool Stack<Type>::isempty()
{
return top == 0;
}
template <class Type>
bool Stack<Type>::isfull()
{
return top == MAX;
}
template <class Type>
bool Stack<Type>::push(const Type & item)
{
if (top < MAX)
{
items[top++] = item;
return true;
}
else
return false;
}
template <class Type>
bool Stack<Type>::pop(Type & item)
{
if (top > 0)
{
item = items[--top];
return true;
}
else
return false;
}
#endif
数据部分:
private:
enum {MAX = 10}; // constant specific to class
Type items[MAX]; // holds stack items
int top; // index for top stack item
其中:items[MAX]是物理容器,必须存在的.MAX是数组长度;top表示当前数组元素个数,同时也是指针,可以获得最后的那个元素items[--top].top值比数组索引值多1.添加第一个元素后,数组里有元素items[0],此时top等于1,依次类推.
初始化:建立数组,把当前元素个数top设为0.
算法:入栈和出栈
指针栈
本书P574,复制代码stcktp1.h,如下:
// stcktp1.h -- modified Stack template
#ifndef ST