如何在类中显示函数

How to display functions in a class

本文关键字:显示 函数      更新时间:2023-10-16

对于我正在进行的项目,我想从命令提示符向用户显示所有可用的功能,现在除了键入每个之外,还有没有显示这些功能

示例:

Functions I want displayed
bool status();
double getTime();
void setTime(int h, int min, int sec);
double getDate();
void setDate(int d,int m,int y);
void setAuto();
void turnOn();
void turnOff();

这些是在我称之为Audio_Visual.h 的类中声明的

//Have a small welcome text
cout << "Welcome to this Home Automation System" << endl;
cout << "Here Are a list of functions, please type what you want to do" << endl;
// DISPLAY FUNCTIONS
//display current function such as lights.setAuto();
string input = "";
//How to get a string/sentence with spaces
cout << "Please enter a valid function" << endl;
getline(cin, input);
cout << "You entered: " << input << endl << endl;

我是如何编写命令行内容的

您可以使用映射将函数名称映射到函数指针

typedef void ( Audio_Visual::* fv)();
std::map<std::string, fv> void_functions;

std::map<std::string, std::function<void(void)> > void_functions;

您需要用于不同签名的不同映射:即

typedef double ( Audio_Visual::* fd)();
std::map<std::string, fd> double_functions;

std::map<std::string, std::function<double(void)> > double_functions;

用法:

Audio_Visual a;
void_functions[ "turnOn"] = &Audio_Visual::turnOn;
std::cout << "Now we are turning on...";
(a.(*void_functions[ "turnOn"]))();

在这里,您可以找到关于第二个选项的更多信息:在一个类中使用具有成员函数的泛型std::function对象

我建议您制作一个<函数名称函数指针>。这通常被称为查找表。

搜索函数名称,然后在同一位置取消引用函数指针。

缺点是所有函数都必须具有相同的签名。

另一种选择是使用Factory设计模式。

在C++中做到这一点并不容易,因为它没有实现反射。

这种构造存在于其他语言中(例如Java和C#)。

C++不支持反射,因此无法迭代类的成员函数。

然而,我建议您将设计分为两部分:"Actions";以及实现本身

不同的操作会做不同的事情(即调用实现端的不同函数)。因此,一个操作就是接受必要的用户输入并调用适当的实现函数。一些简单的例子:

void get_status_action()
{
    //Just propmts the status:
    std::cout << impl.status();
}
void set_time_action()
{
    int hour , minute , second;
    //Get user input:
    std::cout << "Please enter the time: ";
    std::cin >> hour >> minute >> second;
    //Call the implementation:
    impl.steTime( hour , minute , second );
}

现在,您想要的是以用户可以轻松选择的方式存储操作。使用从字符串(操作的名称)到操作的映射注意,在我的示例中,操作只是使用全局实现实例的函数。您可以编写一些复杂的操作实现,如函数、类等)

int main()
{
    std::unordered_map<std::string,std::function<void()>> actions;
    actions["Set status"] = set_status_action;
    actions["Set current time"] = set_time_action;
    while( true )
    {
        //Propmt the actions:
        std::cout << "Select one of the following actions:" << std::endl;
        
        for( auto& pair : actions )
            std::cout << pair.first << std::endl;
        //Read the selection and execute the proper action:
        std::string selection;
        std::getline( std::cin , selection );
        actions[selection]();
    }
}