类中成员函数指针数组初始化编译错误求助(Nix C++)
解决类中成员函数指针数组的初始化编译错误
嘿,我来帮你搞定这个问题!你遇到的编译错误,核心原因是对C++成员函数指针的获取规则理解不到位,咱们一步步来修正:
错误根源
在C++里,成员函数的地址必须显式用&来获取,而且在类外部引用类的成员函数时,必须加上类作用域限定符A::。你之前直接写Func1的写法,编译器无法正确识别这是类A的成员函数指针,所以会报类型不匹配的转换错误。
修正后的完整代码
只需要修改静态数组的初始化语句,补上&和类作用域即可:
#include <iostream> #include <cassert> using namespace std; #define F1 0 #define F2 1 #define F3 2 class A { private: bool Func1(); bool Func2(); bool Func3(); public: bool do_it(int op); typedef bool (A::*fn)(void); static fn funcs[3]; protected: }; // 关键修正:给成员函数加上&和A::作用域 A::fn A::funcs[3] = {&A::Func1, &A::Func2, &A::Func3}; int main() { A Obj; cout << "Func1 returns " << Obj.do_it(F1) << endl; cout << "Func2 returns " << Obj.do_it(F2) << endl; cout << "Func3 returns " << Obj.do_it(F3) << endl; return 0; } bool A::do_it(int op) { assert(op < 3 && op >= 0); return (this->*(funcs[op]))(); } bool A::Func1() { return false; } bool A::Func2() { return true; } bool A::Func3() { return false; }
补充说明
- 你对成员函数指针类型的定义
typedef bool (A::*fn)(void);是完全正确的,它明确了这是指向A类中无参、返回bool类型成员函数的指针。 do_it函数里调用成员函数指针的写法(this->*(funcs[op]))();也没问题,成员函数必须依赖类实例(this指针)才能执行,所以必须用this->*来解引用成员函数指针。
这样修改后,编译器就能正确识别成员函数指针的类型,编译错误就会消失啦!
内容的提问来源于stack exchange,提问作者Mr B
相关产品推荐
相关产品推荐

