类成员变量是一个函数指针,指向这个类的一个成员函数可以吗?
本帖最后由 brucewoo 于 2017-2-15 22:47 编辑大家好,有个比较纠结的问题。
我知道在外部可以使用函数指针来调用一个类的成员函数,但我的问题是,可否在一个类中声明一个函数指针,然后这个指针指向自己这个类中的某个成员函数?
我试了老半天都失败了,网上搜到的信息都没有关于这种情况的,只有外部调用的那种情况。
试验代码,如下:
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);
}
//=============以上是主程序===================
编译给出的错误信息是:
main:14: error: cannot convert 'mytest::func1' from type 'void (mytest::)()' to type 'void (*)()'
exit status 1
cannot convert 'mytest::func1' from type 'void (mytest::)()' to type 'void (*)()'
百思不得其解,是我写错了,还是C++根本就不允许这样的操作?
页:
[1]