如何从其他类调用函数指针

问题描述 投票:1回答:1

假设我有一些带有一些简单函数指针的简单类,如下所示:

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 )();
   }
}

所以这里(this->*funcPointer )();做的工作。

但我无法弄清楚如何使用其他类的funcPointer,我的意思是这样的:

class otherClass
{
    otherClass(){};

    ClassWithFuncPointer instanceOfClassWithFuncPointer;
}

现在我如何在funcPointer成员的otherClass中使用instanceOfClassWithFuncPointer。有可能吗?

我尝试了很多变种:

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

要么

(instanceOfClassWithFuncPointer.*funcPointer)();

要么

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

要不就

instanceOfClassWithFuncPointer.funcPointer();

但总是得到错误。我无法弄清楚。

c++ member-function-pointers
1个回答
0
投票

那么(C ++ 11或更新版本)如下?

auto fp = instanceOfClassWithFuncPointer.funcPointer;

(instanceOfClassWithFuncPointer.*fp)();

或者(兼容C ++ 98,可能使用更短的变量名)?

(instanceOfClassWithFuncPointer.*instanceOfClassWithFuncPointer.funcPointer)();

以下是一个完整的工作示例

#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();
 }
© www.soinside.com 2019 - 2024. All rights reserved.