Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Klassen-Templates sind etwas komplexer als Funktions-Templates. Die Deklaration entspricht aber der von Funktions-Templates. Beispiel 24-2 zeigt die stack-Klasse aus Kapitel 13 als Template.
#include <cstdlib>
#include <iostream>
#include <assert.h>
const int STACK_SIZE = 100; // Maximale Größe des Stack
/********************************************************
* Stack-Klasse *
* *
* Member-Funktionen *
* stack -- initialisiere den Stack. *
* push -- lege ein Element auf den Stack. *
* pop -- hole ein Element vom Stack. *
********************************************************/
// Der Stack selbst
template<typename kind>
class stack {
private:
int count; // Anzahl von Elementen auf dem Stack
kind data[STACK_SIZE]; // die Elemente
Code View:
Scroll
/
Show All public:
// Initialisiere den Stack
stack( ) {
count = 0; // setze die Anzahl auf 0
}
// lege ein Element auf den Stack
void push(const kind item) {
assert(count >= 0);
assert(count < sizeof(data)/sizeof(data[0]));
data[count] = item;
++count;
}
// hole ein Element vom Stack
kind pop( ) {
// Stack wird um eins kleiner
--count;
assert(count >= 0);
assert(count < sizeof(data)/sizeof(data[0]));
// Rückgabe des obersten Wertes
return (data[count]);
}
};
|