next up previous contents index
Nächste Seite: 8.6 Datenkapselung Aufwärts: 8. Der Datentyp Klasse Vorherige Seite: 8.4 Der Zuweisungsoperator   Inhalt   Index


8.5 Der Printoperator

Ein nicht unbedingt notwendiger, aber recht nützlicher Operator ist der Printoperator für eine Klasse, welcher die Datenausgabe mittels

cout << robbi <<endl;

ermöglichen soll.

Die Deklaration in studenten.hh

#include <iostream.h>
//                       output operator
friend ostream & operator<<(ostream  & s, 
                            const Studenten & orig);

erlaubt, dank des Bezeichners friend, die Nutzung der Klasse Studenten zur Definition einer neuen Methode der Klasse ostream (in iostream.h deklariert). Die Definition ist dann:

ostream & operator<<(ostream  & s, const Studenten & orig)
{
 return s << orig.pvorname << " "   << orig.pname << " , "
          << orig.matrikel << " , " << orig.skz; 
}

Nunmehr können wir das Beispiel Ex643-correct.cc (bzw. Ex752.cc) aus §6.4 wesentlich einfacher schreiben und erweitern.

#include <iostream.h>
#include "studenten.hh"

int main()
{
 Studenten robbi;               // Default constructor
 
 {              // start block
                                // Constructor with args
   Studenten arni("Arni", "Schwarz", 812, 7938592);
   
   robbi = arni;                // Assignment operator
   
  }             // end block    // Destructor for arni	

 Studenten mike(robbi);         // Copy constructor
 
 cout << "mike : " << mike << endl;

 cout << endl;
//      Data in Studenten are public therefore:
 cout << "Access to public data : ";
 cout << "mike.pvorname = " << mike.pvorname << endl;

 return 0;
}                               // Destructor for robbi, mike
(siehe Ex851.cc)

Die Kommandozeile
LINUX> g++ Ex851.cc studenten.cc
erzeugt das ausführbare Programm.


Gundolf Haase 2004-01-15