如何在类中显示函数
How to display functions in a class
对于我正在进行的项目,我想从命令提示符向用户显示所有可用的功能,现在除了键入每个之外,还有没有显示这些功能
示例:
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]();
}
}
相关文章:
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- C++ 构造函数未显示输出
- 访问和打印元组中的数据,并使用 C++14 使用模板函数显示数据
- 如何修复加载图标()函数不显示图标?
- 提升堆栈跟踪不显示函数名称和行号
- 如何在函数中显示结构数组
- 如何显示函数开始、结束行和函数体?
- 如何使 Clang Complete 显示函数参数
- Visual Studio 2015 Natvis如何显示函数静态变量
- 如何在模型中显示函数的进度条
- 是否有任何工具可以显示函数中的数据依赖关系
- for 循环在显示函数 OpenGL 中调用的函数中不起作用
- GDB:显示函数将我的 {type} 的地址打印为整数——想改成十六进制
- 如何正确实现类的显示函数
- DLL导出查看器显示函数的完整签名-无法从Java调用它们
- 使用复杂的显示函数会阻止glutKeyboardFunc工作
- GDB 不显示函数名称
- c++中LinkedList调用时的显示函数
- 如何在类中显示函数
- 在过剩显示函数中使用对象