Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

Templates > Klassen-Templates

Klassen-Templates

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.

Example. max-t/stack1.cpp

#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

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]);
        }
};

					  


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial