简体   繁体   English

如何使用动态绑定覆盖纯虚拟 function

[英]How to overwrite a pure virtual function with dynamic binding

I'm attempting to solve exercise 7.3 in the Pitt-Francis text https://link.springer.com/book/10.1007/978-3-319-73132-2 regarding an abstract ODE class.我正在尝试解决 Pitt-Francis 文本https://link.springer.com/book/10.1007/978-3-319-73132-2中关于抽象 ODE class 的练习 7.3。

The abstract class is given as抽象 class 给出为

class AbstractODESolver
{
private:
    ...
    
public:
    ....
    virtual double RightHandSide(double y, double t) = 0;
    virtual double SolveEquation() = 0;
    
};

The derived class is given as派生的 class 给出为

class ForwardEuler: public AbstractODESolver
{
public:
     double RightHandSide(double y, double t);
     double SolveEquation();
};

How would one cast RightHandSide in ForwardEuler so that it may be defined at runtime?如何在 ForwardEuler 中转换 RightHandSide 以便在运行时定义它?

In particular a main file could take the form特别是主文件可以采用以下形式

double RHS(double y, double t);

int main(int argc, char* argv[])
{
    
    AbstractODESolver* p_ODEs = new ForwardEuler;
        
    return 0;
}

double RHS(double y, double t)
{
    return 1+t;
}

and I would like to write something like我想写一些类似的东西

p_ODEs->RightHandSide = &RHS;` 

to point to the function RHS .指向 function RHS

Give the ForwardEuler class a data member to store the function, and pass it in the constructor.ForwardEuler class 一个数据成员来存储 function,并在构造函数中传递它。 The RightHandSide function will just call the function passed in. RightHandSide function 只会调用传入的 function。

class ForwardEuler: public AbstractODESolver
{
public:
    ForwardEuler(std::function<double(double, double)> rhs): rhs(rhs) {}
    double RightHandSide(double y, double t) { return rhs(y, t); }
    double SolveEquation();

private:
    std::function<double(double, double)> rhs;
};

...

double RHS(double y, double t);
AbstractODESolver* p_ODEs = new ForwardEuler(RHS);

Here's my solution that doesn't require std::function , which I think is the required solution given the techniques taught in the chapter.这是我不需要std::function的解决方案,我认为这是本章教授的技术所需的解决方案。

(As per @Paul Sanders) (根据@Paul Sanders)

class ForwardEuler: public AbstractODESolver
{
public:
     ForwardEuler(double (*pRhs)(double, double));
     double RightHandSide(double y, double t);
     double SolveEquation();

private:
     double (*mRhs)(double y, double t);     
};
ForwardEuler::ForwardEuler(double (*pRhs)(double, double))
{
    mRhs = pRhs;
}

double ForwardEuler::RightHandSide(double y,double t)
{
    return (*mRhs)(y,t);
}

main function主function

double RHS(double y, double t);

int main(int argc, char* argv[])
{
    
    AbstractODESolver* p_ODEs = new ForwardEuler(RHS);
    std::cout<<(*p_ODEs).RightHandSide(1.0,1.0)<<std::endl;

    return 0;
}

double RHS(double y, double t)
{
    return 1+t;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM