Überladen virtueller Funktionen C++
-
Hallo!
Kann mir jemand erklären, warum ich im Beispiel unten die überladene
Funktion "doAmazingStuff" mit einem Parameter für ein Objekt der
abgeleiteten Klasse nicht aufrufen kann?#include <iostream> class A { public: void doBoringStuff(double a) { doAmazingStuff(a, a/2); }; public: void doAmazingStuff(double a) { doAmazingStuff(a, a/2); }; virtual void doAmazingStuff(double a, double b) = 0; }; class B : public A { public: void doAmazingStuff(double a, double b) { std::cout << a << " " << b << std::endl; }; }; int main() { A* a = new B; // OK a->doAmazingStuff(8); B b; // OK b.doBoringStuff(8); // Compiler error b.doAmazingStuff(8); return 0; }Nur die Zeile "b.doAmazingStuff(8);" erzeugt folgenden Fehler:
test.cpp:29: error: no matching function for call to
‘B::doAmazingStuff(int)’
test.cpp:16: note: candidates are: virtual void B::doAmazingStuff(double, double)Vielen Dank!
Tobias
-
-
Weil doAmazingStuff(double a) der Klasse A von doAmazingStuff(double a, double b) der Klasse B verdeckt wird.
Der Aufruf sollte gehen:
b.A::doAmazingStuff(8);
-
Alternativ sollte auch gehen:
static_cast<A&>(b).doAmazingStuff(8);