Naor Malca Naor Malca - 1 year ago 86
C++ Question

Storing functions from class in array and invoke them c++

i try store a functions(methods) from class in array and use them.
The error handle is


In function 'int main()':| 'actions' was not declared in this
scope


this my code(i delete unnecessary code)
the class.h:

class Calculator
{
public:
int num1,num2;
void (Calculator::*actions[4])();
void add();
void minuz();
void multi();
void div();
Calculator();
};


class.cpp:

void Calculator::add()
{}
void Calculator::minuz()
{}
void Calculator::div()
{ }
void Calculator::multi()
{}
Calculator::Calculator()
{
actions[0]=add;
actions[1]=minuz;
actions[2]=div;
actions[3]=multi;
}


main:

Calculator cal;
.....
.....
cal.*actions[num]();

Answer Source

C++ syntax for function pointer declaration is quite complicated, so it better use typedefs To call function by pointer you need extra () around dereferenced function pointer. Finally it will be:

class Calculator
{
    public:
        typedef void (Calculator::*action)();
        int num1,num2;
        action actions[4];
        void  add();
        void  minuz();
        void  multi();
        void  div();
        Calculator();
};

void  Calculator::add()
{}
void  Calculator::minuz()
{}
void  Calculator::div()
{ }
void Calculator::multi()
{}
Calculator::Calculator()
{
    actions[0]=&Calculator::add;
    actions[1]=&Calculator::minuz;
    actions[2]=&Calculator::div;
    actions[3]=&Calculator::multi;
}

int main(int, char**) {
    Calculator cal;
    int num = 0;
    (cal.*cal.actions[num])();
    return 0;
}

for better readability I'd suggest add function Calculator::call_by_index(int):

void Calculator::call_by_index(int index)
{
    (this->*actions[index])();
}

and call it in such way:

cal.call_by_index(num);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download