简体   繁体   中英

How to Call function pointer from other class

let's say I have simple class with some simple function pointer, like that:

class ClassWithFuncPointer
{
public:
   inline void firstFunction() { /* do something */ };
   inline void secondFunction() { /* do something */ };

   // MY FUNCTION POINTER
   void (ClassWithFuncPointer::*funcPointer) ();

   // AND I CAN DEFINE IT BY DEFAULT IN CONSTRUCTOR LIKE THAT:
   ClassWithFuncPointer()
   {
       funcPointer = &ClassWithFuncPointer::firstFunction;
   }

   // AND NOW I CAN USE MY FUNCTION POINTER INSIDE OF ClassWithFuncPointer, LIKE THAT:
   void useFunctionPointer()
   {
       (this->*funcPointer )();
   }
}

So here (this->*funcPointer )(); do the job.

But I can't figure it out how to use my funcPointer from other class, I mean something like that:

class otherClass
{
    otherClass(){};

    ClassWithFuncPointer instanceOfClassWithFuncPointer;
}

And now how can I use funcPointer inside otherClass on member of instanceOfClassWithFuncPointer . Is it possible at all?

I tried many variants:

(this->*instanceOfClassWithFuncPointer.funcPointer)();

or

(instanceOfClassWithFuncPointer.*funcPointer)();

or

( (&instanceOfClassWithFuncPointer)->*funcPointer )();

or just

instanceOfClassWithFuncPointer.funcPointer();

but always get error. I can't figure it out.

What about (C++11 or newer only) as follows?

auto fp = instanceOfClassWithFuncPointer.funcPointer;

(instanceOfClassWithFuncPointer.*fp)();

Or also (C++98 compatible, maybe using shorter variable names) ?

(instanceOfClassWithFuncPointer.*instanceOfClassWithFuncPointer.funcPointer)();

The following is a full working example

#include <iostream>

struct ClassWithFuncPointer
 {
   public:
      inline void firstFunction ()
       { std::cout << "cwfp::firstFunction()" << std::endl; }
      inline void secondFunction () 
       { std::cout << "cwfp::secondFunction()" << std::endl; }

      void (ClassWithFuncPointer::*funcPointer) ();

      ClassWithFuncPointer()
       { funcPointer = &ClassWithFuncPointer::firstFunction; }

      void useFunctionPointer()
       { (this->*funcPointer )(); }
 };

class otherClass
 {
   public:
      otherClass ()
       { }

      ClassWithFuncPointer instanceOfClassWithFuncPointer;

      void foo ()
       {
         auto fp = instanceOfClassWithFuncPointer.funcPointer;

         (instanceOfClassWithFuncPointer.*fp)();
       } 
 };

int main ()
 {
   otherClass  oc;

   oc.foo();
 }

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