当我试图用函数指针初始化数组时,出现了一个编译器错误。不使用类,我可以很好地运行代码,但是当我将代码合并到类中时,我会得到错误。我想这更多的是因为我对类用法、作用域解析运算符等的理解有问题。如果能帮助我解决这个问题,我将不胜感激。
#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::fn A::funcs[3] = {Func1, Func2, 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; }
编译器会指出:
15:35:31 **** Build of configuration Debug for project JT ****
make all
make: Warning: File 'objects.mk' has modification time 7.3 s in the future
Building file: ../src/JT.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/JT.d" -MT"src/JT.o" -o "src/JT.o" "../src/JT.cpp"
../src/JT.cpp:141:41: error: cannot convert ‘A::Func1’ from type ‘bool (A::)()’ to type ‘A::fn {aka bool (A::*)()}’
A::fn A::funcs[3] = {Func1, Func2, Func3};
^
../src/JT.cpp:141:41: error: cannot convert ‘A::Func2’ from type ‘bool (A::)()’ to type ‘A::fn {aka bool (A::*)()}’
../src/JT.cpp:141:41: error: cannot convert ‘A::Func3’ from type ‘bool (A::)()’ to type ‘A::fn {aka bool (A::*)()}’
src/subdir.mk:18: recipe for target 'src/JT.o' failed
make: *** [src/JT.o] Error 1
15:35:32 Build Finished (took 1s.64ms)
最佳答案
使用A::fn A::funcs[3] = {&A::Func1, &A::Func2, &A::Func3};
关于c++ - 数组中的函数指针(nix c++),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48350696/