C++ Kurs

Wenn fertig, bitte Fenster schließen

Lösung zur Lektion "Laufzeit-Typinformationen"


// Lösung zu RTTI

// Zuerst Dateien einbinden
#include <iostream>
#include <typeinfo>
#include <ctime>
#include <cstdlib>

using std::cout;
using std::endl;

// Basisklasse für Grafikobjekte
// Diese Klasse muss mind. eine virtuelle Memberfunktion enthalten!
class GBase
{
public:
    virtual void Draw() const = 0;
};

// Klasse für Kreise
class Circle: public GBase
{
public:
    void Draw() const
    {
        cout << "Kreis zeichnen\n";
    }
};

// Klasse für Rechtecke
class Rect: public GBase
{
public:
    void Draw() const
    {
        cout << "Rechteck zeichnen\n";
    }
};

// Klasse für Polygone
class Polygon: public GBase
{
public:
    void Draw() const
    {
        cout << "Polygon zeichnen\n";
    }
};

// Funktion zum zufälligen Erstellen von Grafikobjekten
GBase* ClassFactory()
{

    switch(rand() % 3)
    {
    case 0:
        return new Circle;
    case 1:
        return new Rect;
    case 2:
        return new Polygon;
    }
    return NULL;
}

// main() Funktion
int main()
{
    // Anzahl der zu erstellenden Grafikobjekte
    const int NOOFOBJECTS = 10;
    // Zähler
    int index;

    // Zeigerfeld für Grafikobjekte anlegen
    GBase *pnObjects[NOOFOBJECTS];

    // Zufallszahlen-Generator initialisieren
    srand(static_cast<unsigned>(time(NULL)));

    // Nun 10 zufällige Grafikobjekte erzeugen und ablegen
    for (index=0; index<NOOFOBJECTS; index++)
        pnObjects[index] = ClassFactory();

    // Grafikobjekte ausgeben
    for (index=0; index<NOOFOBJECTS; index++)
        pnObjects[index]->Draw();

    // Die verschiedenen Grafikobjekte zählen
    int noOfCircle = 0;
    int noOfRect = 0;
    int noOfPolygon = 0;
    for (index=0; index<NOOFOBJECTS; index++)
    {
        // Falls Grafikobjekt ein Kreis ist
        if (typeid(*pnObjects[index]) == typeid(Circle))
            noOfCircle++;
        else
            // Falls Grafikobjekt ein Rechteck ist
            if (typeid(*pnObjects[index]) == typeid(Rect))
                noOfRect++;
            else
                // Grafikobjekt ist Polygon
                noOfPolygon++;
    }
    // Anzahl der verschiedenen Grafikobjekte ausgeben
    cout << noOfCircle << " Objekte von Typ " << typeid(Circle).name() << endl;
    cout << noOfRect << " Objekte von Typ " << typeid(Rect).name() << endl;
    cout << noOfPolygon << " Objekte von Typ " << typeid(Polygon).name() << endl;
}