I have develop a functor array without class but fail to write a functor relate to class.

Here is the code without class

int returnOne (void)
{
    int a = 0;
    a++;
    return 10;
}

int returnTwo (void)
{
    int a = 0;
    a++;
    return 20;
}

typedef int (*functor2) (void);
functor2 functors2[2] = {returnOne, returnTwo};
cout<<"Array functor : answer "<<functors2[0]()<<" " <<functors2[1]()<<endl;

Here is the code with class

class SampleClass
{
public:
    int plusfunc (int a, int b);
};

int SampleClass :: plusfunc (int a, int b)
{
    return a + b;
}

typedef int (*functor3) (int a, int b);
SampleClass sc;
functor3 functors3[1] = {sc.plusfunc};
cout<<"Assign to class function : answer "<<functors3[0](1,2)<<endl;

Here is the error:
error: cannot convert 'SampleClass::plusfunc' from type 'int (SampleClass::)(int, int)' to type 'functor3 {aka int ()(int, int)}'|*

Member functions are not the same as regular functions. There is a little more work, here is an example:

class SampleClass
{
public:
    int plusfunc (int a, int b);
};

int SampleClass :: plusfunc (int a, int b)
{
    return a + b;
}

typedef int (SampleClass::*functor3) (int a, int b);

int main(){
 SampleClass sc;
 functor3 f[1] = {&SampleClass::plusfunc};
//note you need an object to call the function that f points to
 cout << (sc.*f[0])(1,1) << endl;
 return 0;
}

http://codepad.org/w6WexeJy

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.