С++ Массив ссылок на методы внутри класса

Рейтинг: 1Ответов: 1Опубликовано: 10.04.2015

Создаю класс внутри которого 2 массива (ранее пытался сделать через 2 класс) Первый содержит имена методов Второй содержит линки на сами методы

Нашел на англоязычном stackoverflow пример с полиморфизмом, адаптировал под себя, ничего не работает.

Помогите разобраться.

using namespace std;

class Controller {
private:
    typedef void (*DynamicFunction)();

    vector<DynamicFunction> menuFunctions;
    vector<string> menuNames;

    int status;

public:
    Controller();
    void Listen();
    void Register(string, DynamicFunction);
    void Invoke(int);

    void Menu();
    void Exit();
};

Controller::Controller(){
    status = 0;

    Register("Меню", Controller::Menu);
    Register("Выход", Controller::Exit);
};

void Controller::Invoke(int index){
    menuFunctions[index]();
};

void Controller::Register(string __name, DynamicFunction __function){
    menuNames.push_back(__name);
    menuFunctions.push_back(__function);
}

void Controller::Listen(){
    int input = 0;

    do {

        Invoke(input);

        if(!status) cin >> input;

    }while(!status);
};

void Controller::Menu(){
    const int menuSize = (const int)menuNames.size();

    for(int i = 0; i < menuSize; i++){
        printf("%d. %s\n", i, menuNames[i]);
    }
};

void Controller::Exit(){
    status = true;
};

Ответы

▲ 3Принят

Объявлять тип надо так:

typedef void (Controller::*DynamicFunction)();

Брать указатель на функцию так:

Register("Меню", &Controller::Menu);
Register("Выход", &Controller::Exit);

Вызывать так:

void Controller::Invoke(int index){
    (this->*menuFunctions[index])();
};

Также у вас ошибка в printf:

for(int i = 0; i < menuSize; i++){
   printf("%d. %s\n", i, menuNames[i].c_str());
}