获取c++中成员函数数组的结果



这是Arduino程序(c++)的一部分。单片机为ESP32。

我定义了一个类。在它里面,我创建了一个成员函数数组。

class IRDN_Padidar_Zone
{
bool callAnimation();  
uint16_t Animate_None(enum_Effect inOut);
uint16_t Animate_Print(enum_Effect inOut);
uint16_t Animate_Print_Random(enum_Effect inOut);
uint16_t Animate_Print_Barfak(enum_Effect inOut);
uint16_t Animate_Print_Laser(enum_Effect inOut);
typedef  uint16_t (IRDN_Padidar_Zone::*animatFunction)(enum_Effect);
animatFunction animations[] = {&IRDN_Padidar_Zone::Animate_None,&IRDN_Padidar_Zone::Animate_Print,&IRDN_Padidar_Zone::Animate_Print_Random,&IRDN_Padidar_Zone::Animate_Print_Barfak,&IRDN_Padidar_Zone::Animate_Print_Laser};
};
bool IRDN_Padidar_Zone::callAnimation(enum_Effect state)
{
uint16_t frameCounter = 0;
frameCounter =  *animations[0](state);
return true;
}

当我在另一个类成员函数callAnimation()中访问这个数组时,我得到以下错误:

error: must use '.*' or '->*' to call pointer-to-member function in 'animations[0] (...)', e.g. '(... ->* animations[0]) (...)'
frameCounter =  *animations[0](state);

如果我将类型定义和函数数组移到类的外部,像这样:

class IRDN_Padidar_Zone
{
bool callAnimation();  
uint16_t Animate_None(enum_Effect inOut);
uint16_t Animate_Print(enum_Effect inOut);
uint16_t Animate_Print_Random(enum_Effect inOut);
uint16_t Animate_Print_Barfak(enum_Effect inOut);
uint16_t Animate_Print_Laser(enum_Effect inOut);
};
typedef  uint16_t (IRDN_Padidar_Zone::*animatFunction)(enum_Effect);
animatFunction animations[] = {&IRDN_Padidar_Zone::Animate_None,&IRDN_Padidar_Zone::Animate_Print,&IRDN_Padidar_Zone::Animate_Print_Random,&IRDN_Padidar_Zone::Animate_Print_Barfak,&IRDN_Padidar_Zone::Animate_Print_Laser};

错误变为:

error: too many initializers for 'uint16_t (IRDN_Padidar_Zone::* [0])(enum_Effect) {aka short unsigned int (IRDN_Padidar_Zone::* [0])(enum_Effect)}'
Animate_From_Up,&IRDN_Padidar_Zone::Animate_From_Down,&IRDN_Padidar_Zone::Animate_From_UpDown,&IRDN_Padidar_Zone::Animate_Kerkerh,&IRDN_Padidar_Zone::Animate_Print_Rain};

我很困惑。我是c++的业余爱好者。请帮帮我。

非静态类方法需要一个对象来运行。正如第一条错误信息所说,当通过指针到方法调用非静态方法时,必须使用.*->*操作符。

同样,当作为类成员使用时,数组需要指定它有多少个元素,即使它有内联初始化式。

试试这个:

class IRDN_Padidar_Zone
{
public:
bool callAnimation(enum_Effect state);  
uint16_t Animate_None(enum_Effect inOut);
uint16_t Animate_Print(enum_Effect inOut);
uint16_t Animate_Print_Random(enum_Effect inOut);
uint16_t Animate_Print_Barfak(enum_Effect inOut);
uint16_t Animate_Print_Laser(enum_Effect inOut);
typedef  uint16_t (IRDN_Padidar_Zone::*animatFunction)(enum_Effect);
animatFunction animations[5] = {&IRDN_Padidar_Zone::Animate_None, &IRDN_Padidar_Zone::Animate_Print, &IRDN_Padidar_Zone::Animate_Print_Random, &IRDN_Padidar_Zone::Animate_Print_Barfak, &IRDN_Padidar_Zone::Animate_Print_Laser};
};
bool IRDN_Padidar_Zone::callAnimation(enum_Effect state)
{
uint16_t frameCounter = (this->*(animations[0]))(state);
return true;
}

在线演示

相关内容

  • 没有找到相关文章

最新更新