C++中模板的使用是泛型編程的一種,當使用模板的時候,不必去考慮一個函數、一個類等對具體數據類型的處理,這樣大大的減少的代碼的數量,提高了程序的效率。當程序中需要使用到一個函數或者類是,編譯器將根據模板生成一個能夠處理特定數據的代碼塊。
模板與函數重載區別在於,當具體實現的功能或行爲一樣,只是處理的數據類型不同時,使用模板;當具體的功能、行爲或函數體的基本一直,函數形參的個數、類型都不一致時,建議使用重載。
再此,感謝小甲魚老師。www.fishc.com
該程序中,只是一個簡單的demo,方便理解類模板與棧,沒有做安全檢查(進棧是棧溢出的檢出,出棧時,棧是否爲空等)
1、頭文件,stack.h
#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
/*
** Copyright (C) QPSOFT.COM All rights reserved.
*/
template <class T>
class Stack
{
public:
Stack(unsigned int size=100);//棧大小
~Stack();
void push(T val);//進棧
T pop();//出棧
private:
unsigned int size;
unsigned int sp;//指向棧中一個位置的指針
T *data;//開闢一個新空間,將首地址給T 類型的指針data
};
#endif // STACK_H_INCLUDED
2、源文件,stack.cpp
#include "stack.h"
//利用構造函數初始化
template <class T>
Stack<T>::Stack(unsigned int size)//Stack<T>::Stack(unsigned int size)中<T>不可少,不然編譯器沒有辦法和普通類做區別
{
this->size=size;//因爲形參與實參同名size,用this->size表明爲類數據成員
data=new T[size];
sp=0;
}
//析構函數
template <class T>
Stack<T>::~Stack()
{
delete []data;
}
//進棧,每進一個元素,sp加1,指向下一個元素地址
template <class T>
void Stack<T>::push(T val)
{
data[sp++]=val;
}
//出棧,必須sp先減一個才能指向最後一個進棧的元素。
//因爲,進棧的時候,每進一個元素,sp加1,指向下一個元素地址
//當進最後一個元素時,sp加一指向了下一個元素地址
template <class T>
T Stack<T>::pop()
{
return data[--sp];
}
3、主函數main.cpp
#include<iostream>
#include<string>
#include "stack.cpp"
using namespace std;
int main()
{
Stack<int> intstack(100);
intstack.push(1);
intstack.push(2);
intstack.push(3);
cout<<intstack.pop()<<endl;
cout<<intstack.pop()<<endl;
cout<<intstack.pop()<<endl;
Stack<string> stringstack(100);
stringstack.push("i love you");
stringstack.push("i like you");
stringstack.push("i miss you");
cout<<stringstack.pop()<<endl;
cout<<stringstack.pop()<<endl;
cout<<stringstack.pop()<<endl;
return 0;
}
//顯示結果,先進後出
/*
3
2
1
i miss you
i like you
i love you
*/