结构,成员函数作为参数

时间:2014-11-27 12:19:15

标签: c++ class struct member-functions scope-resolution

我是C ++和堆栈交换的初学者。我正在开发一个接口类,它接收键盘输入并通过循环遍历包含要比较的字符串和输出字符串的结构数组来检查它是否正确,这取决于它是否等于比较字符串。如果输入正确,它将在结构中打印字符串,并调用结构中的函数并执行某些操作。

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

我的问题在于这些行

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

我知道这个是通过类的成员函数传递的,但我不知道如何解决这个问题。我不确定问题是否是struct对象中的范围解析运算符,因为我可以在参数之外使用它。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您应该执行以下操作:

#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

虽然我建议使用functor object over函数指针。

相关问题