Ich gehe durch ein C++ Quiz. Und es kam der folgende Code - es ist illegal, aber ich kann nicht verstehen, warum. Kann mir jemand erklären, warum diese Linie:Vererbung - warum ist das illegal?
Box* b1 = s1->duplicate();
den Fehler Compiler generiert, „kann nicht von Shape * zu Box umwandeln“? Ich nahm an, dass s1->duplicate()
ruft Box::duplicate()
, weil s1
tatsächlich auf eine Box
zeigt - aber vom Compiler-Fehler sieht es aus wie es ruft Shape::duplicate()
.
#include <iostream>
struct Shape
{
virtual Shape* duplicate()
{
return new Shape;
}
virtual ~Shape() {}
};
struct Box : public Shape
{
virtual Box* duplicate()
{
return new Box;
}
};
int main(int argc, char** argv)
{
Shape* s1 = new Box;
Box* b1 = s1->duplicate();
delete s1;
delete b1;
return 0;
}
Wegen [t sein] (http://stackoverflow.com/questions/4665117/c-virtual-function-return-type). –