c++ - 如何调用已保存在自定义结构向量中的成员函数指针?
问题描述
我的问题实际上是关于已经提出的问题。我已经尝试了@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
*/
}
}
};
解决方案
您的第一次尝试失败,因为命名范围内没有变量m_func
。
您的第二次尝试失败,因为指向成员的指针需要调用对象。
正确的语法是:
classFuncPtr fun = bindClassPtr->m_func;
(this->*fun)(str);
对象中包含的指针MyBind
实际上并没有绑定到任何东西。它是一个指向 的成员的指针MyClass
,因此您必须为它提供一个实例MyClass
来处理。
推荐阅读
- python - 假设我将数字作为字符串或十六进制或整数,并且我想转换为整数。我正在寻找更通用的形式
- python - Python:CountVectorizer 忽略一个字母单词“I”
- salt-stack - 使用在支柱中定义的角色定位奴才
- ruby - 将字符串与Ruby中文件中的字符串进行比较
- java - java.lang.IllegalArgumentException:不是 Spring Boot 应用程序中的托管类型
- spss - 变量包含特定文本字符串时的语法
- javascript - 计算控件的数量并将其 ID 打印到警报框中
- node.js - Nginx 将代理传递给另一个 nodejs 服务器
- c# - 如何将 PrintPageEventArgs 添加到 Form_Load c#
- python - 如何为python unittest编写多个assertLessEqual方法