简体   繁体   中英

How do I create and array of pointers to functions?

gcc 6.4.0 win 7 Netbeans 8.2

I can't figure what I'm doing wrong.

#ifndef TYPEDEF_H
#define TYPEDEF_H

class Typedef {
   class Alphabet { };
   class Tuple { };
   class Operations { };
public:
   void test();
private:
   Tuple constant(long one, long two, Alphabet& bet, Operations& op) { return Tuple(); } ;
   Tuple expression(long one, long two, Alphabet& bet, Operations& op) {return Tuple(); } ;
};

#endif /* TYPEDEF_H */

===================== .cpp file ========================
#include "Typedef.h"

void Typedef::test() {
   typedef Tuple (*fn)(long, long, Alphabet&, Operations&);
   fn func[]      = { constant, expression };
   Tuple (*fnc[2])= { constant, expression };
}

Typedef.cpp: In member function 'void Typedef::test()':

Typedef.cpp:6:44: error: cannot convert 'Typedef::constant' from type 'Typedef::Tuple (Typedef::)(long int, long int, Typedef::Alphabet&, Typedef::Operations&)' to type 'fn {aka Typedef::Tuple (*)(long int, long int, Typedef::Alphabet&, Typedef::Operations&)}' fn func[] = { constant, expression };

The error message is repeated for all four instances. I've tried &constant and as expected it didn't work.

A class member function is special in that it accepts an additional invisible argument, the this* pointer. Also, a member function and a free function are completely different types, even if the latter had the extra argument compatible with the this* type.

To capture a pointer to the member function, use the member pointer syntax ( Typedef::* ), like this:

void Typedef::test() {
  typedef Tuple (Typedef::*fn)(long, long, Alphabet&, Operations&);
  fn func[] = { &Typedef::constant, &Typedef::expression };
}

In addition, an address of a member function can be taken only on fully-qualified names (reference: [expr.unary.op]/4 ), so you have to use &Typedef::constant, &Typedef::expression .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM