1

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

接口.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();

};

接口.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

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

任何帮助将不胜感激。

4

1 回答 1

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;
}

现场示例在这里

尽管我建议在函数指针上使用仿函数对象。

于 2014-11-27T12:24:31.487 回答