Seite 1 von 1

Virtuelle Vergleichsoperatoren

Verfasst: 1. Mai 2009 21:34
von Willi2793
Der Titel sagt in etwa was ich gerne hätte. Ich weiß aber auch das dies irgendwie wenig Sinn macht. Aber vielleicht gibt es ja Alternativen auf die ich nicht komme. Ich versuche also mal mein Problem zu schildern.

Ich habe zuerst mal folgende Struktur:

Code: Alles auswählen

class Base {
}

class A1 : public Base {
}

class A2 : public Base {
}
Das sind meine Grundklasse für die Unterlisten (gleich genauer). Dann noch folgendes dazu:

Code: Alles auswählen

class Satz {
    QList<Base*> liste;
}
Die QList von Base* fülle ich mit "new A1()" oder mit "new A2()". Und dann gibt es noch folgendes

Code: Alles auswählen

QList<Satz*> hauptliste;
Dabei ist es absolut sicher gestellt das in einer Instanz von "Satz" in "liste" nur Elemente von A1 oder A2 sind. Niemals ist "liste" gemischt. Ich hoffe das war verständlich.

Nun mein Problem: Ich möchte den Inhalt von "liste" mit "qSort" sortieren. Dazu benötige ich aber eine Implemantation von "operator<". Wie stelle ich das am geschicktesten an? denn einfach "virtual bool operator<(...)" geht nicht (oder ich stelle mich zu blöd an).

Grüße,
Willi

Verfasst: 1. Mai 2009 23:40
von franzf
Du kannst in operator<() für Base schauen, ob sich Base in A1 oder A2 casten lässt. Schneller geht es (Programmlaufzeit), wenn du du in "Base" ein enum "Type" definierst, welches Werte für Base, A1, A2 enthält, und dann erst castest. Dann kannst du eine eigene Vergleichsfunktion auf die gecasteten Werte zum Vergleich anwenden.

Ist aber schon spät, und vllt. gehts ja auch anders.

Gute Nacht
Franz

Verfasst: 4. Mai 2009 10:11
von Willi2793
Vielen Dank für den Tip.

Ich habe es jetzt so gelöst:

Code: Alles auswählen

class Base {
    virtual bool operator<(const Base&) const = 0;
} 

class A1 : public Base { 
    bool operator<(const Base&) const;
    bool operator<(const A1&) const;
} 

class A2 : public Base { 
    bool operator<(const Base&) const;
    bool operator<(const A2&) const;
}
Implementation in A1:

Code: Alles auswählen

bool operator<(const Base& b) const {
    return operator<((A1&)b);
}

bool operator<(const A1& b) const {
    ... Implementation ...
}
Implementation in A2:

Code: Alles auswählen

bool operator<(const Base& b) const {
    return operator<((A2&)b);
}

bool operator<(const A2& b) const {
    ... Implementation ...
}
Das klappt zumindest :)