如何在类中显示函数

时间:2014-04-09 13:07:52

标签: c++

对于我正在研究的项目,我想从命令提示符向用户显示可用的所有可用功能,现在无论如何都要显示这些功能而不是输入每个功能

示例:

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;

我是如何编写命令行的东西

4 个答案:

答案 0 :(得分:1)

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

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"]))();

您可以在此处找到有关第二个选项的更多信息:Using generic std::function objects with member functions in one class

答案 1 :(得分:0)

在C ++中执行此操作并不容易,因为它没有实现Reflection

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

答案 2 :(得分:0)

我建议你制作一个&lt; 函数名称函数指针&gt;的表。这通常称为查找表。

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

缺点是所有功能必须具有相同的签名。

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

答案 3 :(得分:0)

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

但是我建议你将dessign分成两部分:&#34; Actions&#34;以及实施本身

不同的操作会执行不同的操作(即调用实现方的不同功能)。因此,操作是需要用户输入并调用正确的实现函数的操作。一些简单的例子:

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]();
    }
}