64,654
社区成员
发帖
与我相关
我的任务
分享
class mytest
{
public:
void(*fp)(); //一个成员变量,用来指向类内成员函数
void run()
{
fp=func1;
fp();
};
void func1()
{
Serial.println("This is func1 !");
};
void func2()
{
Serial.println("This is func2 !");
};
};
//=============以上是类定义===================
mytest mytest1;
void setup() {
Serial.begin(9600);
}
void loop() {
mytest1.run();
delay(1000);
}
//=============以上是Arduino主程序===================
class mytest
{
public:
void(mytest::*fp)(); //一个成员变量,用来指向类内成员函数
void run()
{
fp=func1;
fp();
};
void func1()
{
Serial.println("This is func1 !");
};
void func2()
{
Serial.println("This is func2 !");
};
};
编译器给出的错误信息是:
error: cannot convert 'mytest::func1' from type 'void (mytest::)()' to type 'void (*)()'
请帮忙再看一下,谢谢。void(mytest::*fp)(); //一个成员变量,指针,用来指向类内成员函数
fp = &mytest::func2; //对该指针赋值
(this->*fp)(); //使用该指针指向的函数
方法二:
typedef void(mytest::*fptype)(); //定义一个类型,指针,用来指向类内成员函数
fptype fp = &mytest::func2; //定义改类型的实例,并赋值
(this->*fp)();//使用该指针指向的函数
class mytest
{
public:
//void(*fp)(); //一个成员变量,用来指向类内成员函数
typedef void(mytest::*fp)();
void run();
void func1();
void func2();
};
//================cpp=================
void mytest:: run()
{
//fp=func1;
//fp = &mytest::func1;
fp pfunc = &mytest::func1;
//fp();
//(this->*fp)();
pfunc();
};
void mytest:: func1()
{
Serial.println("This is func1 !");
};
void mytest:: func2()
{
Serial.println("This is func2 !");
};
错误信息:
must use '.*' or '->*' to call pointer-to-member function in 'pfunc (...)', e.g. '(... ->* pfunc) (...)'
class mytest
{
public:
void(*fp)(); //一个成员变量,用来指向类内成员函数
void run();
void func1();
void func2();
};
//================cpp=================
void mytest:: run()
{
//fp=func1;
fp = &mytest::func1;
//fp();
(this->*fp)();
};
void mytest:: func1()
{
Serial.println("This is func1 !");
};
void mytest:: func2()
{
Serial.println("This is func2 !");
};
错误信息:
main:18: error: cannot convert 'void (mytest::*)()' to 'void (*)()' in assignment
main:20: error: '((mytest*)this)->mytest::fp' cannot be used as a member pointer, since it is of type 'void (*)()'
exit status 1
cannot convert 'void (mytest::*)()' to 'void (*)()' in assignment
typedef void(mytest::*fp)(); //定义函数指针类型
fp pfunc = &mytest::func1;
fp();
fp = &mytest::func1;
(this->*fp)();