类模板定义+用类模板写一个入栈出栈的程序

类模板和函数模板定义类似,都可以看成由模板头和模板体两部分组成。类模板体是一个完整的类。

template<typename 形参名1, template 形参名2,……>

class 类名

{

    // …

};

 

例子:用模板类写一个入栈出栈的程序

#include<iostream>

 

using namespace std;

 

template <typename T, unsignedint N>

class Stack

{

private:

unsignedint index;

T a[N];

public:

Stack():index(){ }

boolpush(const T &value);

T&pop();

boolfull(){ return index == N; }

boolempty(){ return (index == 0); }

unsignedint size(){ return index; }

unsignedint capacity(){ return N; }

};

 

template <typename T, unsigned int N>

bool Stack <  T, N > ::push(const T &value) //特别注意, 在外部编写成员函数时,类名后面指明类型时候只需要类型名,不需要typename关键字!

{

 

if((index <= N - 1) && (index >= 0))

{

a[index++]= value;

returntrue;

}

else

{

returnfalse;

}

 

}

 

template <typename T, unsigned int N>

T& Stack < T, N > ::pop()

{

returna[--index];

}

 

int main()

{

Stack<int, 6> a;//在定义对象的时候也要<>用于指定参数名的数据类型

inti = 10;

 

cout<< "Push Stack......" << endl;

while(!a.full())

{

cout<< "Push " << i << " to Stack" <<endl;

a.push(i++);

}

cout<< endl;

cout<< "Stack data depths: " << a.size() << endl;

cout<< "Stack capacity depths " << a.capacity() <<endl;

cout<< "Pop Stack......" << endl;

while(!a.empty())

{

cout<< "Pop " << a.pop() << "from Stack"<< endl;

}

cout<< endl;

cout<< "Stack data depths: " << a.size() << endl;

cout<< "Stack capacity depths " << a.capacity() <<endl;

 

system("pause");

return0;

}

阅读更多

没有更多推荐了,返回首页