c++ 類模板

1,stack.h

#ifndef STACK_H_
#define STACK_H_


//1,定義類模板,
//模板類開頭代碼:
//template <class Type> 或者 template <typename Type>

//模擬一個棧的模板類
template <class Type>
class Stack
{
private :
	const static int MAX = 100; //棧容納的最多數據
	Type items[MAX];            //儲存棧數據的數組
	int top;                   //棧頂

public:
	Stack();
	bool isempty();
	bool isfull();
	bool push(const Type & item);
	bool pop(Type & 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 & itme)
{
	if(top < MAX)
	{
		items[top++] = itme;
	
		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
2,mian 

//使用模板類
#include "stack.h"
#include <iostream>
#include <string>
using namespace std;

void main()
{
	Stack<int>oneInt;
	int i = 0;
	while(!oneInt.isfull())
	{
		oneInt.push(i++);
	}

	while(!oneInt.isempty())
	{

		int a;
		oneInt.pop(a);
		cout.width(2); //設置輸出寬度
		cout << a;
		a % 10 == 0 ? cout << "\n" : cout << " ";
		/*
		輸出結果:
		99 98 97 96 95 94 93 92 91 90
		89 88 87 86 85 84 83 82 81 80
		79 78 77 76 75 74 73 72 71 70
		69 68 67 66 65 64 63 62 61 60
		59 58 57 56 55 54 53 52 51 50
		49 48 47 46 45 44 43 42 41 40
		39 38 37 36 35 34 33 32 31 30
		29 28 27 26 25 24 23 22 21 20
		19 18 17 16 15 14 13 12 11 10
		9  8  7  6  5  4  3  2  1  0
		*/
	}
	cout << "\n";

	Stack<string> twoString;
	i = 0;

	while(!twoString.isfull())
	{	
		string str = "a";
		char ch = (i++) + '0';
		if(i == 10)
		{
			i = 0;
		}
		str += ch;
		twoString.push(str);
	}

	int a = 99;
	while(!twoString.isempty())
	{
		string str;
		twoString.pop(str);
		cout << str;
		(a --) % 10 == 0 ? cout << "\n" : cout << " ";
		/*
		輸出結果:
		99 98 97 96 95 94 93 92 91 90
		89 88 87 86 85 84 83 82 81 80
		79 78 77 76 75 74 73 72 71 70
		69 68 67 66 65 64 63 62 61 60
		59 58 57 56 55 54 53 52 51 50
		49 48 47 46 45 44 43 42 41 40
		39 38 37 36 35 34 33 32 31 30
		29 28 27 26 25 24 23 22 21 20
		19 18 17 16 15 14 13 12 11 10
		9  8  7  6  5  4  3  2  1  0
		*/
	}
	system("pause");
}


發佈了42 篇原創文章 · 獲贊 16 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章