Wie kann ich zwei Zeiger auf eine Schnittstelle verwenden, um die richtige Funktion aufzurufen, die implementierende KlaC++

Programme in C++. Entwicklerforum
Anonymous
 Wie kann ich zwei Zeiger auf eine Schnittstelle verwenden, um die richtige Funktion aufzurufen, die implementierende Kla

Post by Anonymous »

Ich würde gerne wissen, wie ich den folgenden Code richtig zum Laufen bringen kann.
Mit der Vererbung können Sie die Funktion eines übergeordneten Zeigers aufrufen und die untergeordnete Funktion ausführen. Aber wenn es zwei übergeordnete Zeiger gibt, weiß ich nicht, wie ich jeden Zeigertyp „materiell“ machen soll.
Unten ist ein Beispiel, das dem, was ich zum Laufen bringen möchte, sehr nahe kommt:

Code: Select all

class Shape {
bool intersects(const Circle& other) const = 0;
bool intersects(const Line& other) const = 0;
}

class Circle : public Shape {
bool intersects(const Circle& other) const;
bool intersects(const Line& other) const;
}

class Line : public Shape {
bool intersects(const Circle& other) const;
bool intersects(const Line& other) const;
}

bool intersect(Shape* s1, Shape* s2) {
// this does not compile.
return s1->intersects(*s2);
}
Die Implementierung von intersect kann stattdessen auch global sein:

Code: Select all

class Shape {
}

class Circle : public Shape {
}

class Line : public Shape {
}

bool intersect(const Circle& s1, const Circle& s2) const;
bool intersect(const Circle& s1, const Line& s2) const;
bool intersect(const Line& s1, const Circle& s2) const;
bool intersect(const Line& s1, const Line& s2) const;

bool intersect(Shape* s1, Shape* s2) {
// this does not compile.
return intersect(*s1, *s2);
}
Wie kann ich das erreichen?
Wenn möglich, möchte ich die manuelle Überprüfung von typeid zur Laufzeit oder von „dynamic_cast“ vermeiden, bis ich einen Nicht-Null-Zeiger erhalte.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post