我正在尝试制作函数存储库。我创建了四个文件:
Function.hpp, Function.cpp, FunctionsRepository.hpp, FunctionsRepository.cpp
我想vector
指针保持对函数pointers
。
/FunctionsRepository.hpp
#ifndef FUNCTIONSREPOSITORY_HPP
#define FUNCTIONSREPOSITORY_HPP
#include <vector>
using namespace std;
class FunctionsRepository {
private:
static vector<double *> pointerToFunctions;
public:
static void addFunction(double * wsk);
};
#endif
函数存储库.cpp
#include "FunctionsRepository.hpp"
void FunctionsRepository::addFunction(double * wsk) {
pointerToFunctions.push_back(wsk);
}
//Functions.hpp
#ifndef FUNCTIONS_HPP
#define FUNCTOINS_HPP
#include "FunctionsRepository.hpp"
int constFunction(int numberOfVehicles);
void linearFunction();
void stepFunction();
#endif
功能.cpp
#include "Functions.hpp"
double constFunction(double numberOfVehicles){
return numberOfVehicles/2;
}
double (*funcConstant)(double) = constFunction;
//ERROR HERE
FunctionsRepository::addFunction(funcConstant);
我想尽可能轻松地向程序添加新函数,并在程序的其他部分中使用它。
但我不明白。为什么我收到此错误。addFunction()
方法是静态的,这意味着我可以在其他类或程序部分使用它。static
Vector 以确保它是整个程序的唯一一个副本。
使用函数包装器。 std::function 可以存储可调用的对象。因此,您的代码将包含如下内容:
class FunctionsRepository {
private:
// void() - function prototype
static std::vector<std::function<void()>> pointerToFunctions;
public:
static void addFunction(std::function<void()> wsk)
{
pointerToFunctions.push_back(wsk);
}
};
有关更多信息,请参阅官方文档:http://en.cppreference.com/w/cpp/utility/functional/function
我解决了。我收到错误,因为我在任何范围之外调用FunctionsRepository::addFunction(funcConstant);
表达式。我刚刚创建了新函数来执行此命令,仅此而已。