C++类模板入门
基本格式:
template
class 类名
{
protected:
T a;
public:
void func()
{
}
…
…
};
类外定义函数:
templete
void 类名::func()
{
…
}
主函数中调用(实例化):
类名<具体的变量类型> 对象(可选的参数列表)
以数组形式的堆栈为例:
#include
using namespace std;
template
class Stack
{
protected:
int max_size;//最大长度
int top;//栈顶元素
T *stackptr;//取值数组
public:
Stack(int s)
{
max_size = s > 0 ? s:10;//保证最大长度
top = -1;//初始化栈顶元素
stackptr = new T[max_size];//为取值数组分配空间
}
~Stack()
{
delete []stackptr;
}
bool isempty() const
{
return (top == -1);//用比较运算符表示一个判断,决定返回的值
}
bool isfull() const
{
return(top == max_size - 1);
}
bool push(const T &t)
{
if(!isfull())
{
stackptr[++top] = t;
return true;
}
else
{
return false;
}
}
bool pop(T &t)
{
if(!isempty())
{
t = stackptr[top–];
return true;
}
else
{
return false;
}
}
};
int main()
{
Stack double_stack(5);
double f = 0.1;
cout << “压栈打印:” << endl;
while(double_stack.push(f))
{
cout << f << “,” << endl;
f += 1;
}
cout << “…” << endl;
cout << “出栈打印:” << endl;
while(double_stack.pop(f))
{
cout << f << endl;
}
return 0;
}