获取 class 成员函数的地址并从指针调用它

Getting address of class member function and calling it from pointer

正在尝试为 Arduino 制作 LCD 屏幕库。 做了一个class"ScreenHandlerClass"。这有 S1_stat() 和 S2_stat() 函数,可以在 LCD 屏幕上写不同的东西。 有一个 "statScreenPointer",我正在尝试调用函数,但它无法正常工作。

我试着遵循这个指南: Calling Member Function Pointers 这是我的问题最接近的解决方案。 我试过了:

这个->*statScreenPointer

Error compiling project sources
ScreenHandler.cpp: 14:26: error: invalid use of non-static member function
   this->*statScreenPointer

其他我试过的: 这个->*statScreenPointer()

Error compiling project sources
ScreenHandler.cpp: 14:27: error: must use '.*' or '->*' to call pointer-to-member function in '((ScreenHandlerClass*)this)->ScreenHandlerClass::statScreenPointer (...)', e.g. '(... ->* ((ScreenHandlerClass*)this)->ScreenHandlerClass::statScreenPointer) (...)
   this->*statScreenPointer()
Build failed for project 'v1'

代码:

// ScreenHandler.h

#ifndef _SCREENHANDLER_h
#define _SCREENHANDLER_h

#include "arduino.h"
#include "debug.h"
#include "vezerles.h"
#include "EncoderHandler.h"
#include <LiquidCrystal_I2C.h>

extern EncoderHandlerClass encoder;
extern LiquidCrystal_I2C lcd;

enum screenType {
    S1,
    S2
};

extern screenType screen;

class ScreenHandlerClass
{
private:
    void logic();
    void (ScreenHandlerClass::*statScreenPointer)();

public:
    ScreenHandlerClass();
    void init();
    void handle();
    void S1_stat();
    void S2_stat();
};

#endif

// ScreenHandler.cpp
#include "ScreenHandler.h"

screenType screen;

ScreenHandlerClass::ScreenHandlerClass() {}

void ScreenHandlerClass::init() {

    statScreenPointer = &ScreenHandlerClass::S1_stat;
    this->*statScreenPointer; // ----> how to call this properly?
    lcd.setCursor(0, 1);
    lcd.print("init"); // this is DISPLAYED
}

void ScreenHandlerClass::handle()
{
    logic();
}

void ScreenHandlerClass::logic()
{
    // some logic for lcd screen switching
}

void ScreenHandlerClass::S1_stat() {
    lcd.setCursor(0, 0);
    lcd.print("S1_stat"); // this is NOT DISPLAYED
}

void ScreenHandlerClass::S2_stat() {
    // some other text for lcd
}
// v1.ino
#include "debug.h"
#include "global.h"
#include <TimerOne.h>                  
#include <LiquidCrystal_I2C.h>          
#include "MillisTimer.h"
#include "vezerles.h"
#include "lcd.h"
#include "EncoderHandler.h"
#include "ScreenHandler.h"

extern EncoderHandlerClass encoder;
ScreenHandlerClass scrh;
LiquidCrystal_I2C lcd(0x3F, 20, 4);

void setup() {
    Serial.begin(9600);
    encoder.initButton(PIND, PD4, 500);
    lcd.init();
    lcd.backlight();
    scrh.init();

}
void loop() {
    // some code
}


函数调用运算符 () 的优先级高于取消引用运算符 *。这意味着您需要括号来调用 member-function 指针:

(this->*statScreenPointer)();

您想要的语法是(如您的链接问题中所述):

(this->*statScreenPointer)();