i watched video can found @ https://www.youtube.com/watch?v=4f72vulwfvc , liked of concept cases presented. working linked list , need selective method execution, example:
#include <stdio.h> class { public: a() : next(0) { if (head == 0) { head = this; } else { a* step = head; while (step->next != 0) { step = step->next; } step->next = this; } } virtual ~a() { if (head == this) { head = 0; } else { a* step = head; while (step->next != this) { step = step->next; } step->next = next; } } virtual void foo() { // nothing... } static a* head; a* next; }; class b : public { public: b() {} virtual ~b() {} virtual void foo() { printf("function foo\n"); } }; a* a::head = 0; int main() { a_cls; b b_cls; a* step = a::head; while (step != 0) { step->foo(); step = step->next; } return 0; } after instantiating of objects, method foo() of objects of class b need execute. achieve this, virtual method foo() added class a, empty body, virtual void foo() {}, , in class b, code added method foo() body.
it works not it, in main function looks doing @ each node, not, feels null pointer. there creative solution this?
note: using c++03.
check out dynamic_cast way check particular derived type , call foo on objects of class b (or class derived b):
int main() { a_cls; b b_cls; a* step = a::head; b* step_b = 0; while (step != 0) { step_b = dynamic_cast<b *>(step); if (step_b != 0) { step_b->foo(); } step = step->next; } return 0; } this way, there's no need define empty foo method on a. try out on ideone.
Comments
Post a Comment