【问题标题】:pass multiple class function pointer as function parameter in c++在c ++中将多个类函数指针作为函数参数传递
【发布时间】:2021-08-26 10:52:04
【问题描述】:

我正在学习函数指针,并且能够在类之间传递函数指针。 现在我正在寻找接收所有其他类的函数指针参数。

fncptr2.h

 #ifndef FNCPTR2
 #define FNCPTR2

 class fncptr1;

 class fncptr2
 {
    public:
      int implfncptr(int (fncptr1::*add)(int,int));
 }; 

 #endif 

fncptr2.cpp

#include "fncptr2.h"
#include "fncptr1.h"
#include <iostream>

using namespace std;

fncptr1 ff;

int fncptr2::implfncptr(int (fncptr1::*add)(int, int))
{
   return (ff.*add)(1,2);
}

fncptr1.h

#ifndef FNCPTR1
#define FNCPTR1

class fncptr1
{
  public:
    int addition(int a,int b);
    void testfncptr();

};

#endif 

fncptr1.cpp

   #include "fncptr1.h"
#include "fncptr2.h"
#include <iostream>

using namespace std;

int fncptr1::addition(int a,int b)
{
    return a + b;
}

void fncptr1::testfncptr()
{
   fncptr2 f;
   f.implfncptr(&fncptr1::addition);
 }

ma​​in.cpp

fncptr1 f;
f.testfncptr();

上面的示例代码工作正常。现在希望在

中接收所有函数指针
int implfncptr(int (fncptr1::*add)(int,int));

不是接收 fncptr1 函数指针,而是希望从所有其他类接收函数指针

例子

int implfncptr(int (AllClassInstance::*add)(int,int));

【问题讨论】:

  • 你的问题不太合理。您是否建议您想要一个更通用的答案?

标签: c++ function-pointers


【解决方案1】:

好的,您的问题不太合理,但听起来您想要的是一个更通用的解决方案。首先,我不会像您使用函数指针那样使用它们。这是非常 C 风格的,还有更好的方法。我对“更好”的定义是“适合更多解决方案”。我喜欢的方式可能会对性能造成非常轻微的影响。

 #include <functional>

 class Foo {
 public:
     typedef std::function<bool(std::string &)> MyFunct;

     void someMethod(MyFunct funct) {
         std::string str = "Foo";
         if (funct(str)) {
             ...
         }
     }
 };

 // Then somewhere else, you can do this:


 bool f(const std::string &str) {
     return str.length() > 10;
 }

 Foo foo;
 foo.someMethod(f);

但我喜欢这个的原因是你也可以使用 lambdas:

 Foo foo;
 foo.someMethod([](const std::string &str) { return str.length() > 10; });

或者您可以像这样预先定义 lambda:

 Foo::MyFunct f = [](const std::string &str) { return str.length() > 10; };

 foo.someMethod(f);

我不知道这是否真的能帮助你推进你想做的事情,因为在我写这个答案时你的问题还不是很清楚。但这可能有助于提供一些其他方法来完成您想要的。

我确信 C 风格的函数指针是有争议的,但在我看来,函数式接口提供了更好的特性。

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 2022-01-20
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2017-01-08
    • 2010-09-05
    • 1970-01-01
    • 2021-10-05
    相关资源
    最近更新 更多