How do you declare a const array of function point

2019-02-16 10:09发布

Firstly, I've got functions like this.

void func1();
void func2();
void func3();

Then I create my typedef for the array:

void (*FP)();

If I write a normal array of function pointers, it should be something like this:

FP array[3] = {&func1, &func2, &func3};

I want to make it a constant array, using const before "FP", but I've got this error messages:

error: cannot convert 'void ( * )()' to 'void ( * const)()' inialization

PD: Sorry my bad English.

EDIT:

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};

My code is more large and complex, this is a summary

5条回答
\"骚年 ilove
2楼-- · 2019-02-16 10:26

Then I create my typedef for the array: void (*FP)();

Did you miss typedef before void?

Following works on my compiler.

 void func1(){}
 void func2(){}
 void func3(){}

 typedef void (*FP)();


 int main()
 {
     const FP ar[3]= {&func1, &func2, &func3};
 }

EDIT

(after seeing your edits)

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];
 };
查看更多
一夜七次
3楼-- · 2019-02-16 10:27

Which compiler are you using? This works on 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;
}
查看更多
来,给爷笑一个
4楼-- · 2019-02-16 10:29
    typedef void (*FPTR)();

FPTR const fa[] = { f1, f2};
// fa[1] = f2;  You get compilation error when uncomment this line.
查看更多
小情绪 Triste *
5楼-- · 2019-02-16 10:30

If you want the array itself to be const:

FP const a[] =
    {
        func1,
        func2,
        func3
    };
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-02-16 10:35

without typedef:

void (*const fp[])() = {
    f1,
    f2,
    f3,
};
查看更多
登录 后发表回答