也许我是用这个问题离开左边的领域,但是有可能通过构造函数定义成员函数吗?通过构造函数初始化成员函数
在我的情况下,我想写一个类来执行健壮的模型拟合(使用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;
}
我想我已经在我的例子bastardized正确的语法,但我希望这个问题是清楚的。基本上我问:构造函数是否可以接受函数指针作为参数并将它们赋值为成员函数的实现?
其次,即使这是可能的,它被认为是不好的形式吗?
更新:如果有帮助,here is MATLAB code for robust estimation有这种一般化结构的我希望能复制在C++
的回答你的问题是**是**。并在'double'中更正你的代码;'和这个分号是为了什么? –
@ k-five:错字,对不起。是的,这可能吗?或者是的,这是不好的形式?或两者? – marcman
尽管[*** Pimpl idiom ***](http://stackoverflow.com/questions/60570/why-should-the-pimpl-idiom-be-used)可能是更好的方法。 –