通过构造函数初始化成员函数
Initialize member functions via constructor
也许我对这个问题有点不了解,但有可能通过构造函数定义成员函数吗?
在我的案例中,我试图编写一个类来执行稳健的模型拟合(使用RANSAC)。我希望这可以推广到不同类型的模型中。例如,我可以使用它来确定对一组3D点的平面的估计。或者,也许我可以确定两组点之间的转换。在这两个例子中,可能需要不同的误差函数和不同的拟合函数。静态函数调用可能看起来像,而不是使用类
model = estimate(data, &fittingFunc, &errorFunc);
我想知道我是否可以为那些模块化函数提供成员实例?
类似的东西
class Estimator
{
private:
// estimation params
double errorFunc(std::vector<dtype>, double threshold); // Leave this unimplemented
double fittingFunc(std::vector<dtype>, Parameters p); // Leave this unimplemented
public:
Estimator(void (*fittingFunc(std::vector<dtype>, Parameters), void (*errorFunc(std::vector<dtype>, double));
dtype estimate(data); // Estimates model of type dtype. Gets implemented
};
Estimator::Estimator(void (*fittingFunc(std::vector<dtype>, Parameters), void (*errorFunc(std::vector<dtype>, double))
{
fittingFunc = fittingFunc;
errorFunc = errorFunc;
}
我想我已经在我的例子中破坏了正确的语法,但我希望问题是清楚的。基本上,我在问:构造函数是否可以接受函数指针作为参数,并将其分配为成员函数的实现
第二,即使这是可能的,它是否被认为是糟糕的形式?
更新:如果有帮助的话,这里是用于稳健估计的MATLAB代码,它具有我希望在C++中复制的这种可推广结构
构造函数是否可以接受函数指针作为参数,并将其分配为成员函数的实现?
否。不是成员函数。但是您当然可以拥有公共成员函数指针:
class Estimator
{
public:
double (*errorFunc)(std::vector<dtype>, double threshold);
double (*fittingFunc)(std::vector<dtype>, Parameters p);
public:
Estimator(void (*fittingFunc(std::vector<dtype>, Parameters), void (*errorFunc(std::vector<dtype>, double))
: errorFunc(errorFunc)
, fittingFunc(fittingFunc)
{ }
dtype estimate(data);
};
为了获得更好(或更安全)的接口,您可以将函数指针设为private
,并拥有一个只需调用它们的公共成员函数。
更一般地说,如果您对开销满意,您可以拥有类型为std::function<double(std::vector<dtype>, double)>
和std::function<double(std::vector<dtype>, Parameters)>
的成员,然后您可以使用更广泛的可调用对象(函数指针,但也包括lambda、绑定成员函数等)
是的,您可以为拟合和误差函数提供算法。您可以使用指向函数的指针来完成此操作。还有一个更好的解决方案,在标准标头中,您可以找到模板std::函数,它可以用指向函数的指针构造,也可以用函子或lambda表达式构造。
你的课应该是这样的:
#include <functional>
class Estimator
{
private:
// estimation params
using error_func_type = std::function<double(std::vector<dtype>,double)>;
using fitting_func_type = std::function<double(std::vector<dtype>,Parameters p)>;
fitting_func_type fittingFunc;
error_func_type errorFunc;
public:
Estimator(fitting_funct_type fit, error_funct_type err)
:fittingFunc(fit),errorFunc(err){}
dtype estimate(data); // Estimates model of type dtype. Gets implemented
};
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法