首页 > 解决方案 > 如何调用已保存在自定义结构向量中的成员函数指针?

问题描述

我的问题实际上是关于已经提出的问题。我已经尝试了@r3mus n0x 给出的答案,也看到了一些 SO 问题,这些问题并没有帮助我清楚地了解上述情况。

在给定的帖子中缺少 MCVE,因此我尝试了一些并提出了以下代码,并且出现了与@user10213044 在他/她的帖子中提到的相同的错误。

错误信息

error C2065: 'm_func': undeclared identifier

我的问题:

Q1:我们真的可以将指向类的某些成员函数的指针(如下例所示)存储到它的私有成员(例如向量数组)中吗?如果是这样,上述错误消息的原因是什么?

Q2:我也尝试在 for 循环中编写:

classFuncPtr fun = bindClassPtr->m_func; // compiles
fun(str); // error

给了我:错误信息

error: must use '.*' or '->*' to call pointer-to-member function in 'fun (...)', e.g. '(... ->* fun) (...)'
 fun(str); // error

我无法理解。谁能告诉我在这种情况下出了什么问题?

第二次尝试类似于我们用于普通函数指针情况的以下情况。

typedef void(*FuncPtr)(const std::string&);
FuncPtr Lambda = [](const std::string& str) { std::cout << str << std::endl; };
Lambda(std::string("Hellow World"));

这是我尝试过的代码:

#include <iostream>
#include <vector>
#include <string>
#include <memory>

class MyClass;          
typedef void (MyClass::*classFuncPtr)(const std::string&); // function ptr to MyClass::member functions

struct MyBind // bind struct
{
   classFuncPtr m_func;
   explicit MyBind(const classFuncPtr& func): m_func(std::move(func)) {}
};

class MyClass
{
    std::string m_var;
    std::vector<std::unique_ptr<MyBind>> my_binds_;
public:
   MyClass() // constructor 
   {
      my_binds_.emplace_back( std::make_unique<MyBind>( std::move(&MyClass::do_this) ));
      my_binds_.emplace_back( std::make_unique<MyBind>( std::move(&MyClass::do_that) ));
   }

   // two functions to bind
   void  do_this (const std::string& str) { std::cout << "From do this: " << str << std::endl;   }
   void  do_that (const std::string& str) { std::cout << "From do that: " << str << std::endl;   };

   void handle_input(const std::string& str)
   {

      for (const std::unique_ptr<MyBind>& bindClassPtr: my_binds_)
      {
          // how to print passed string str here??              (Q1)
          (bindClassPtr->*m_func)(str);

          /*
          classFuncPtr fun = bindClassPtr->m_func; // compiles   (Q2)
          fun(str); // error
          */
      }
   }
};

标签: c++c++11c++14member-function-pointers

解决方案


您的第一次尝试失败,因为命名范围内没有变量m_func

您的第二次尝试失败,因为指向成员的指针需要调用对象。

正确的语法是:

classFuncPtr fun = bindClassPtr->m_func;
(this->*fun)(str);

现场演示

对象中包含的指针MyBind实际上并没有绑定到任何东西。它是一个指向 的成员的指针MyClass,因此您必须为它提供一个实例MyClass来处理。


推荐阅读