我正在尝试编写一组通用数学实用程序类(根查找器、积分器等),它们在构造一个指向基类的指针时接受,该基类定义了我希望特定算法对其进行操作的函数。基类应该只定义一个type operator()(type inputArg)
可由用户根据需要实现的公共虚拟接口(抽象或具有默认琐碎功能)。这将允许用户只实现所需的函子并执行所需的计算。我的mwe如下:
第一个头文件定义了抽象接口类
// BaseFunctor.h
#ifndef _BASE_FUNCTOR_H_
#define _BASE_FUNCTOR_H_
class BaseFunctor
{
public:
virtual double operator() (double x) = 0;
};
#endif
这是求解器方法之一的类
// NewtonsMethod.h
#ifndef _NEWTONS_METHOD_H_
#define _NEWTONS_METHOD_H_
class BaseFunctor;
class NewtonsMethod
{
public:
NewtonsMethod(BaseFunctor *rhsIn,
BaseFunctor *rhsPrimeIn,
double x0In);
~NewtonsMethod();
bool DetermineRoot(double &root);
private:
double x0;
BaseFunctor *rhs;
BaseFunctor *rhsPrime;
static const double EPSILON;
static const unsigned int MAX_ITER;
};
#endif
这是求解器实现: // NewtonsMethod.cpp
#include "NewtonsMethod.h"
#include "BaseFunctor.h"
#include <cmath>
const double NewtonsMethod::EPSILON = 1e-9;
const unsigned int NewtonsMethod::MAX_ITER = 30;
NewtonsMethod::NewtonsMethod(BaseFunctor *rhsIn,
BaseFunctor *rhsPrimeIn,
double x0In) :
rhs (rhsIn),
rhsPrime(rhsPrimeIn),
x0 (x0In)
{ }
NewtonsMethod::~NewtonsMethod() { }
bool NewtonsMethod::DetermineRoot(double &root)
{
// This is obviously not implemented
root = rhs(1.0) / rhsPrime(2.0);
return false;
}
以及我进行派生类实现的主要功能:// Main.cpp
#include "BaseFunctor.h"
#include "NewtonsMethod.h"
#include <iostream>
#include <iomanip>
class fOfX : public BaseFunctor
{
double operator() (double x)
{
return x * x - 2.0;
}
};
class fPrimeOfX : public BaseFunctor
{
double operator() (double x)
{
return 2.0 * x;
}
};
int main()
{
double x0 = 2.0;
BaseFunctor *f = new fOfX();
BaseFunctor *fPrime = new fPrimeOfX();
NewtonsMethod newton(f, fPrime, x0);
double root = 0.0;
bool converged = newton.DetermineRoot(root);
if (converged)
{
std::cout << "SUCCESS: root == " << std::setprecision(16) << root << std::endl;
}
else
{
std::cout << "FAILED: root == " << std::setprecision(16) << root << std::endl;
}
delete f;
delete fPrime;
}
我试图让它尽可能简短,如果太长,请见谅。基本上我得到了错误:
g++ Main.cpp NewtonsMethod.cpp -o main
NewtonsMethod.cpp: In member function ‘bool NewtonsMethod::DetermineRoot(double&)’:
NewtonsMethod.cpp:29: error: ‘((NewtonsMethod*)this)->NewtonsMethod::rhs’ cannot be used as a function
NewtonsMethod.cpp:29: error: ‘((NewtonsMethod*)this)->NewtonsMethod::rhsPrime’ cannot be used as a function
我怎样才能解决这个问题,保持所需的功能或为各种需要的功能派生一个类?
谢谢