FAQ 38.04 How is an array of pointers to nonstatic member functions declared?

Use a typedef.

Consider the following class example.

 #include <iostream> using namespace std; class Fred { public:   void f(int i);   void g(int i);   void h(int i); }; void Fred::f(int i)   { cout << "Fred::f(int); i=" << i << '\n'; } void Fred::g(int i)   { cout << "Fred::g(int); i=" << i << '\n'; } void Fred::h(int i)   { cout << "Fred::h(int); i=" << i << '\n'; } typedef void (Fred::*FredMemberPtr)(int); 

Since FredMemberPtr is a typedef, it can be used like most other data types. In particular, an array of FredMemberPtr can be created using the following syntax.

 FredMemberPtr array[3] = { &Fred::f, &Fred::g, &Fred::h }; 

To call one of the nonstatic member functions, supply a Fred object, and use the .* operator.

 int main() {   Fred x;   for (int i = 0; i < 3; ++i) {     FredMemberPtr p = array[i];     (x.*p)(42 + i);   } } 

The output of this program is as follows.

 Fred::f(int); i=42 Fred::g(int); i=43 Fred::h(int); i=44 


C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net