【发布时间】:2015-01-26 06:50:41
【问题描述】:
谁能解释我为什么会收到这个错误?
我正在开发一个接口类,它获取键盘输入并通过循环遍历包含要比较的字符串和要输出的字符串的结构数组来检查它是否正确,具体取决于它是否等于比较字符串.如果输入正确,它将打印结构中的字符串,并调用结构中的函数并执行一些操作。
interface.hpp
#include <string>
class Input_Interface {
public:
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();
private:
std::string input_str;
};
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
我知道 this 是通过类的成员函数传递的,但我不知道如何解决这个问题。我不确定问题是否是导致错误的结构对象内的范围解析运算符,因为我可以在结构之外使用它就好了。 Clear() 和 Quit() 不能是静态的,因为它必须能够访问类中的对象。
【问题讨论】:
-
函数不是 C++ 中的对象;您不能分配功能。也许您正在寻找函数指针或指向成员函数的指针?
-
函数确实是 C++ 中的对象,您可能会想到 C。您可以使用 std::function
-
std::is_object不同意你的观点。 -
我想你是对的。我所说的是Functors(函数对象),它不同于函数,你可以让函数表现为对象。
-
我很清楚这一点(确实会出现在答案中)。我只是指出为什么您的代码不起作用。
标签: c++ class struct scope member-functions