Well, I am writing a game that has a paired class (enemy) vector that will be filled with child classes (goomba, koopa, boss1), and I need to do this when I invoke the update, it invokes the corresponding update for the child classes. I managed to create an example of my problem.
#include <stdio.h> class A{ public: virtual void print(){printf("Hello from A");} }; class B : public A{ public: void print(){printf("Hello from B");} }; int main(){ A ab = B(); ab.print(); while(true){} }
Requires output: "Hello from B" The result is received: "Hello from A"
How do I get it to call print function B?
. B A, A, B, . ""; B "" , .
B
A
, B* A*, A*, - B, B - , B .
B*
A*
Try:
int main(){ A* ab = new B(); ab->print(); delete ab; while(true){} }
B A& (reference-to-A),
A&
int main(){ B b; A& ab = b; ab.print(); while(true){} }
, .
You need to call the parent update method before any processing by descendant classes:
struct Base_Class { virtual void update(void) { cout << "Updating Base_Class.\n"; } }; struct Goomba : public Base_Class { void update(void) { // Invoke the parent method first. Base_Class::update(); // Perform Descendant operations cout << "Updating Goomba\n"; } };
Here is the implementation:
#include <iostream> using std::cout; void Update_Player(Base_Class& b) { b.update(); return; } int main(void) { Goomba g; g.update(); Goomba g2; std::vector<Base_Class *> container; container.push_back(&g); container.push_back(&g2); std::vector<Goomba>::iterator iter; for (iter = container.begin(); iter != container.end(); ++iter) { Update_Player(*(*iter)); } return 0; }
Source: https://habr.com/ru/post/1747596/More articles:JavaScript cookie cannot be found in Django - javascriptState template. Why doesn't the context class implement or inherit abstract abbreviations / class? - design-patternsJavascript form validation only works in firefox - javascriptDo I need JDK or just JRE? - javaDo java.security.Key.getEncoded () return DER encoded data? - javajquery is sorted with regex - jquery-uiAuthentication of multiple organizational units in Active Directory - c #ΠΡΠ»Π°Π΄ΠΊΠ° WCF Π² Windows 7 x64 - visual-studio-2008Delphi How to track URLs loaded by IE? - internet-explorerAddField type image and sketch path - imageAll Articles