//Menu.h
#include<iostream>
#include<conio.h>
#include <map>
#include <string>
#include <functional>
#include <utility>
using namespace std;
map<string,function< void() > > mapa;
string names[100];
string functions[100];
char keys[100];
int pos=0;
void menu(string name,char key,string functionc)
{
names[pos]=name;
keys[pos]=key;
functions[pos]=functionc;
mapa.insert(map<string,function< void()> >::value_type(functionc,functionc));
pos++;
}
void write()
{
for(int i=0;i<pos;i++)
{
cout<<names[pos]<<" ";
cout<<endl;
}
}
错误:错误1 错误 C2064:项未计算函数 取 0 个参数
//Main.cpp
#include <iostream>
#include <map>
#include <string>
#include"Menu.h"
using namespace std;
void ime()
{
cout<<"k";
}
int main() {
menu("ime1",'c',"ime");
pisi();
system("PAUSE");
return 0;
}
我想使标题通用,以便用户可以制作菜单。它将引用它的名称以及需要按哪个字符才能访问其功能用户将制作自己的函数,然后从标题中使用它。
C++不支持
这一点。您需要一个名为反射的编程语言属性。
请改用脚本语言。
我可以通过这样更改您的代码来编译它:
#include <iostream>
#include <conio.h>
#include <map>
#include <string>
#include <functional>
#include <utility>
using namespace std;
map<string,string > mapa;
string names[100];
string functions[100];
char keys[100];
int pos=0;
void menu(string name,char key,string functionc)
{
names[pos]=name;
keys[pos]=key;
functions[pos]=functionc;
mapa.insert(std::make_pair(functionc,functionc));
pos++;
}
void write()
{
for(int i=0;i<pos;i++)
{
cout<<names[pos]<<" ";
cout<<endl;
}
}
我担心顶部的menu.h评论 - 这是一个头文件吗?现在,它已经对编译错误进行了排序,但可能不会执行您想要的操作。您想要名称到函数的映射吗?
std::map<std::string, std::function<void()>> strings_to_functions;
例如,函数不带参数并返回 void
void fn1()
{
std::cout << "fn1n";
}
我现在可以将其添加到地图中,
strings_to_functions.insert(std::make_pair("fn1", fn1));
并称它
strings_to_functions["fn1"]();
您试图从此处的std::string
进行std::function<void()>
:
map<string,function< void()> >::value_type(functionc,functionc)
// ^^^^^^^^^
您需要传递一些没有参数的可调用内容,返回void
.例如:
void foo() {};
mapa.insert(std::make_pair(functionc, foo));
//MENU.h
#include<iostream>
#include<conio.h>
#include <map>
#include <string>
#include <functional>
#include <utility>
using namespace std;
map<string,function< void() > > mapa;
string names[100];
string functions[100];
char keys[100];
int pos=0;
void menu(string name,char key, function< void() >functionc)
{
names[pos]=name;
keys[pos]=key;
functions[pos]=functionc;
mapa.insert(std::make_pair(name,functionc));
pos++;
}
//Main.cpp
#include <iostream>
#include <map>
#include <string>
#include"Menu.h"
using namespace std;
void ime()
{
cout<<"k";
}
int main() {
menu("ime1",'c', ime);
pisi();
system("PAUSE");`enter code here`
return 0;
}