c – 使用成员函数作为参数的结构
作者:互联网
我是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对象中的范围解析运算符,因为我可以在参数之外使用它就好了.
任何帮助将不胜感激.
解决方法:
你应该做一些如下所示的事情:
#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;
}
虽然我建议使用functor object over函数指针.
标签:member-functions,c,class,struct,scope-resolution 来源: https://codeday.me/bug/20191007/1867066.html