struct with member function as parameter

2019-02-15 23:58发布

I am a beginner in C++ and stack exchange. I am working on an Interface class that gets keyboard input and checks to see whether it is correct through looping through an array of structs which contains strings to compare to and strings to output depending if it is equal to the compare string or not. If the input is correct, it will print the string within the struct and a function within the structure is called and does some action.

interface.hpp

#include <string>
class Input_Interface {
    struct command_output {
    std::string command;
    std::string success_string;
    std::string failure_string;
    void output_function();
    }

    bool stop_loop = false;
    void Clear();
    void Quit_loop();

};

interface.cpp

#include <iostream>
void Input_Interface::Quit_loop() {
   stop_loop = true;
   // ends loop and closes program
}

void Input_Interface::clear() {
   // does some action
}

Input_Interface::command_output clear_output{"CLEAR", "CLEARED", "", Input_Interface::Clear()};
Input_Interface::command_output quit_output{"QUIT", "GOODBYE", "", Input_Interface::Quit_loop()};
Input_Interface::command_output output_arr[]{clear_output, quit_output};

void Input_Interface::begin() {
while (stop_loop == false) {
    Input_Interface::get_input(); //stores input into var called input_str shown later
    this->compare_input();
    }
}

void Input_Interface::compare_input() {
for (unsigned int i=0; i<2; i++) {
    if (this->input_str == output_arr[i].command) {
        std::cout << output_arr[i].success_string << std::endl;
        output_arr[i].output_function();
        break;
        }
    }
    // ... goes through else for failure printing invalid if it did not match any of the command string in the command_output struct array

My issue is with these lines

Input_Interface::command_output clear_output{"CLEAR", "CLEARED", "", Input_Interface::Clear()};
//error: call to non-static function without an object argument

Input_Interface::command_output quit_output{"QUIT", "GOODBYE", "", Input_Interface::Quit_loop()};
//error: call to non-static function without an object argument

I know this is passed through member functions of the class but I don't know how to go about fixing this problem. I'm not really sure if the problem is the scope resolution operator inside the struct object or not because I can use it outside of parameters just fine.

Any help would be greatly appreciated.

1条回答
放我归山
2楼-- · 2019-02-16 00:36

You should do something as shown below:

#include <string>
struct Input_Interface {
    struct command_output {
      std::string command;
      void (*output_function)();
    };

    static void Clear();
    static void Quit_loop();
};

int main() {
    Input_Interface::command_output t = {"CLEAR", Input_Interface::Clear};
    return 0;
}

Live example here

Although I would suggest using a functor object over function pointer.

查看更多
登录 后发表回答