c++ - 从结构数组调用指向成员的函数
问题描述
我遇到了似乎是语法问题。查看其他 StackOverflow 答案并没有给我一个适用于我的问题的答案。至少不是我能理解的。
我的调度程序类:
#define MAX_TASKS 10
typedef struct taskProps {
int interval;
int elapsedTime;
int (Controller::*taskFunction)(void);
} taskProps;
class TaskScheduler {
public:
TaskScheduler();
int setUpdateInterval(int interval);
int addTask(int interval, int (Controller::*taskFunction)(void));
int startTimer();
void clearTasks();
int checkTasks();
private:
int numberOfTasks;
int updateInterval;
taskProps scheduledTasks[MAX_TASKS];
};
这一切都编译得很好,但问题在于调用此函数中的成员函数指针:
int TaskScheduler::checkTasks(){
int tasksExecuted = 0;
for(int i = 0; i < numberOfTasks; i++){
if(scheduledTasks[i].elapsedTime >= scheduledTasks[i].interval){
scheduledTasks[i].taskFunction;
scheduledTasks[i].elapsedTime = 0;
tasksExecuted++;
}
scheduledTasks[i].elapsedTime += updateInterval;
}
return tasksExecuted;
}
编译它给了我错误;
../Core/Src/TaskScheduler.cpp:88:22: warning: statement has no effect [-Wunused-value]
其他尝试:
scheduledTasks[i].*taskFunction;
../Core/Src/TaskScheduler.cpp:88:23: error: 'taskFunction' was not declared in this scope
scheduledTasks[i].taskFunction();
../Core/Src/TaskScheduler.cpp:88:35: error: must use '.*' or '->*' to call pointer-to-member function in '((TaskScheduler*)this)->TaskScheduler::scheduledTasks[i].taskProps::taskFunction (...)', e.g. '(... ->* ((TaskScheduler*)this)->TaskScheduler::scheduledTasks[i].taskProps::taskFunction) (...)'
任何人都可以帮助我并解释我在这里缺少哪些知识?
解决方案
当您想调用成员函数指针时,您使用的语法是
(object_of_type_mem_func_pointer_points_to.*function_pointer)(parameters)
或者
(pointer_to_object_of_type_mem_func_pointer_points_to->*function_pointer)(parameters)
不幸的是,(scheduledTasks[i].*taskFunction)()
这不起作用,因为taskFunction
需要一个Controller
对象来调用taskFunction
。这需要更像这样的代码:
(controller_object.*(scheduledTasks[i].taskFunction))()
或者
(pointer_to_controller_object->*(scheduledTasks[i].taskFunction))()
推荐阅读
- delphi - 如何使用 FireDAC 提取存储过程 DDL
- reactjs - 纱线启动时将 src/ 文件夹更改为其他内容
- nginx - 如何将基本身份验证放在 ngnix 入口中的特定 HTTP 方法上?
- c# - 强制 Json 属性合并到列表/数组中
- flume-ng - 配置具有多个通道的水槽时数据通道锁定错误
- python - 安装 pip 包时出现错误 1 (pycrypto)
- neo4j - 如何使用节点和关系获取模式变量(如果存在)
- python - 有没有办法用 Scrapy 和 Python 为不包含该节点的特定类放置一个空白条目来代替节点值
- android - 在 Android 上的视图模型中使用 Dagger 2 单例
- android - 用 MySQL 扑动无限滚动视图