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

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

template

class 类名

{

    // …

};

 

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

#include

 

using namespace std;

 

template

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

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

{

 

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

{

a[index++]= value;

returntrue;

}

else

{

returnfalse;

}

 

}

 

template

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

{

returna[--index];

}

 

int main()

{

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

inti = 10;

 

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

while(!a.full())

{

cout<< "Push " << i << " to Stack" <

a.push(i++);

}

cout<< endl;

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

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

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() <

 

system("pause");

return0;

}

你可能感兴趣的:(C++)