获取类成员函数的地址并从指针中调用

时间:2019-05-10 16:24:16

标签: c++ arduino function-pointers member-function-pointers

试图为Arduino制作LCD屏幕库。 制作了一个类“ ScreenHandlerClass”。它具有S1_stat()和S2_stat()函数,可以在LCD屏幕上写入不同的内容。 我正在尝试创建一个“ statScreenPointer”来调用函数,但是它不能正常工作。

我试图遵循此指南: Calling Member Function Pointers 那是最接近我的问题的解决方案。 我尝试过:

this-> * statScreenPointer

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

我尝试过的其他: this-> * 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
}


2 个答案:

答案 0 :(得分:0)

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

(this->*statScreenPointer)();

答案 1 :(得分:0)

所需的语法是(如链接的问题所述):

(this->*statScreenPointer)();