首先,我有这样的功能。
void func1();
void func2();
void func3();
然后我为数组创建了typedef:
void (*FP)();
如果我写一个正常的函数指针数组,它应该是这样的:
FP array[3] = {&func1, &func2, &func3};
我想在“FP”之前使用 const 使其成为常量数组,但我收到此错误消息:
PD:抱歉我的英语不好。错误:无法将'void(*)()'转换为'void(* const)()'inialization
编辑:
x.h
typedef void (*FP)();
class x
{
private:
int number;
void func1();
void func2();
void func3();
static const FP array[3];
}
x.cpp
const FP x::array[3] = {&x::func1, &x::func2, &x::func3};
我的代码更大,更复杂,这是一个摘要
答案 0 :(得分:8)
然后我为数组创建了typedef:
void (*FP)();
您在typedef
之前错过了void
吗?
以下是我的编译器。
void func1(){}
void func2(){}
void func3(){}
typedef void (*FP)();
int main()
{
const FP ar[3]= {&func1, &func2, &func3};
}
<强> x.h 强>
class x;
typedef void (x::*FP)(); // you made a mistake here
class x
{
public:
void func1();
void func2();
void func3();
static const FP array[3];
};
答案 1 :(得分:4)
没有typedef
:
void (*const fp[])() = {
f1,
f2,
f3,
};
答案 2 :(得分:3)
您使用的是哪种编译器?这适用于VS2005。
#include <iostream>
void func1() {std::cout << "func1" << std::endl;}
void func2() {std::cout << "func2" << std::endl;}
void func3() {std::cout << "func3" << std::endl;}
int main()
{
int ret = 0;
typedef void (*FP)();
const FP array[3] = {&func1, &func2, &func3};
return ret;
}
答案 3 :(得分:2)
typedef void (*FPTR)();
FPTR const fa[] = { f1, f2};
// fa[1] = f2; You get compilation error when uncomment this line.
答案 4 :(得分:1)
如果您希望数组本身为const:
FP const a[] =
{
func1,
func2,
func3
};