【发布时间】:2020-03-29 04:29:03
【问题描述】:
#include <iostream>
#include<string>
#include<vector>
#include<functional>
using namespace std;
void straightLineMethod();
void unitsOfActivity();
void decliningMethod();
int main()
{
using func = std::function<void()>;
string inputMethod;
string depreciation[3] = { "straight line","units of activity","declining" };
std::vector<func> functions;
functions.push_back(straightLineMethod);
functions.push_back(unitsOfActivity);
functions.push_back(decliningMethod);
cout << " Enter the method of depreciation you're using: " << depreciation[0] << ", " << depreciation[1] << " , or " << depreciation[2] << endl;
cin.ignore();
getline(cin, inputMethod);
for (int i = 0; i <functions.size() ; i++) {
while(inputMethod == depreciation[i])
{
functions[i]();
}
}
我尝试研究答案并了解如何使用std::function,但我并不完全理解它的作用。在网上很难找到与这个问题相关的答案。本质上,我想要的是将三个函数放在一个向量中,将用户输入与字符串数组进行比较,然后使用数组中的索引来使用向量中的相关索引来调用函数。这对我来说似乎是个好主意,但它失败了。在这种情况下使用.push_back 尝试填充向量给了我一个
E0304 error: no instance of overloaded function matches the argument list.
Edit: Specifically, I dont know what the syntax: using func= std::function<void()> is actually doing. I just added it to the code to try to get it to work , thats why my understanding is limited in troubleshooting here.
Edit: the E0304 error is fixed by correcting the syntax to reference the function instead of calling it. And i changed functions[i] to functions[i]() to call the functions, although it is still not working.
【问题讨论】:
-
您对它们有什么不了解的地方?这将帮助人们根据您的需求定制响应。写解释只是为了发现你已经理解了其中的一部分是没有用的。
-
stackoverflow.com/questions/1112584/stdvector-of-functions 他们在这个帖子上回答了同样的问题,请查看
-
你知道你的代码永远不会终止吗?
-
@TanveerBadar 为什么会这样?
-
while循环,一旦进入,永远不会终止。
标签: c++ function vector using func