Pointers to member functions
I have a class for recording/logging errors (CErr), and I would like it to be able to record stuff in various ways; either in a file, a win32 console, or message box. I thought having a pointer to a function (one func for each method) would be a good way to do this, but I''m at a loss as to how to get pointers to functions. I''ve tried quite a few things and nothing has worked.. and I can''t find anything about it in the documentation I''ve looked at. So, can someone give me a clue?
Thanks.
Do you want a function pointer or a method pointer?
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara
Method pointer, if your terminoligy is what I think it is.
I.e, both the pointer and the funcs it points to are members of the same class.
I.e, both the pointer and the funcs it points to are members of the same class.
Here''s some sample code for using pointers to member functions:
The & in the constructor is necessary in ANSI C++, but MS will let you leave it out.
The key is the .* or the ->* operators, which let you call the function pointer on the right of the operator with the class on the left of the operator.
class A { public: void (A::*func_ptr)(void); void FuncA(void) { printf("A\n"); } void FuncB(void) { printf("B\n"); } void FuncC(void) { printf("C\n"); } void FuncD(void) { (this->*func_ptr)(); } A() { func_ptr = &A::FuncA; }};int main(int argc, char ** argv) { A a; a.FuncD(); a.func_ptr = A::FuncB; (a.*(a.func_ptr))(); a.func_ptr = A::FuncC; a.FuncD(); return 0;}
The & in the constructor is necessary in ANSI C++, but MS will let you leave it out.
The key is the .* or the ->* operators, which let you call the function pointer on the right of the operator with the class on the left of the operator.
I read about this the other day. I may be totally wrong though(i am new to this.)
if you have a Class CErr, with a member function error(),
Now, if you wanted to call the member function of the object with a pointer, you can do it 2 ways:
Hope this wasn't too basic. I just saw it the other day in my book, and i basically copied out(with different examples)
Dong
Edited by - dong on November 9, 2000 6:05:33 PM
if you have a Class CErr, with a member function error(),
CErr a;CErr *p;p = &a
Now, if you wanted to call the member function of the object with a pointer, you can do it 2 ways:
p -> error();(*p) .error();
Hope this wasn't too basic. I just saw it the other day in my book, and i basically copied out(with different examples)
Dong
Edited by - dong on November 9, 2000 6:05:33 PM
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement