简体   繁体   中英

How to call virtual function for all created objects which are inherited from the one? C++

For example, I have three classes: A, B::A and C::A, only B and C have virtual method print(), like that:

#include <iostream>

using namespace std;

class A {
public:
    virtual void print() {
        return;
        //do nothing
    }

    static void Func() {
        //how to call all virtual functions print() for one class A?
        print(); //doesn't work
    }
};

class B : public A {
public:
    virtual void print() {
        cout << "B" << endl;
    }
};

class C : public A {
public:
    virtual void print() {
        cout << "C" << endl;
    }
};

int main() {
  B b1;
  B b2
  C c;
  A::Func();
  return 0;
}

I wan't use print() for all inherited objects (b1, b2, c) by using just class A. How can I do it?

Declare a static class member of A that's a container of pointers to all instances of A or its subclasses. A std::list will be an excellent choice:

class A {
   static std::list<A *> all_instances;
public:

   // ...
};

In A's constructor, add its this to the list, saving the new list entry's iterator. In A's destructor, remove its list entry from the list.

So now you will have a private container that enumerates all instances of A , or any of its subclasses.

Writing a static class method that invokes each one's print() method becomes trivial, at this point.

Of course, a little bit of additional work is necessary to implement thread safety, if it's an issue here.

Writing the code for A's constructor or destructor will be your homework assignment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM