模拟函数指针 [英] Simulate function pointer

查看:238
本文介绍了模拟函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下类包含应使用回调技术计算积分的方法。

The following class contains a method that should calculate the integral using the callback technique.

package integrals;

import java.lang.*;

public class Integrals 
{
    public static double f1(double x)
    {
        return x*5+Math.sin(x);
    }   

    public static double f2(double x)
    {
        return Math.pow(x*f1(-x),x);      
    }        

    public static double TrapezoidalIntegration(double a,double b,int n,double (*f)(double))
    {
        double rValue=0;
        double dx;

        dx=(b-a)/n;

        for(double i=f(a);i<f(b);i+=dx)
            rValue+=((f(i)+f(i+dx))*dx)/2.0;

        return rValue;
    }        

    public static void main(String[] args) 
    {


    }
}

如何在这种情况下进行回调?我喜欢避免☞这种解决方案,因为它的复杂性和丑陋。即使这是最痛苦的,我也不知道如何在这里实现它。

How to make a callback in this case? I prefer to avoid ☞such solution☜ due to it's complexity and ugliness. Even if it is the least painful, I don't have an idea how to implement it here.

推荐答案


如何在这种情况下进行回调?我喜欢避免此类解决方案,因为它的复杂性和丑陋。即使这是最痛苦的,我也不知道如何在这里实现它。

How to make a callback in this case? I prefer to avoid such solution due to it's complexity and ugliness. Even if it is the least painful, I don't have an idea how to implement it here.

由于Java中没有函数指针,因此必须使用公共接口。你的功能然后必须是该接口的实现。它是由你决定是否要为那些实现类(例如类F1 extends Function {...} )或匿名类(例如 new Function {...} )。它也取决于你是否在该类中编写imp0lementation,或者让类实现调用你现有的一个静态函数。

Since there are no function pointers in Java, you have to use a common interface instead. Your functions then have to be implementations of that interface. It is up to you whether you want to use names for those implementing classes (i.e. class F1 extends Function { … }) or anonymous classes instead (i.e. new Function { … }). It is also up to you whether you write the imp0lementation inside that class, or instead have the class implementation call one of your existing static functions.

举个例子,用匿名直接包含实现的类:

Taking one example, with anonymous classes directly containing the implementation:

public class Integrals 
{

    public interface Function {
        double eval(double x);
    }

    public static final Function f1 = new Function() {
      public double eval(double x) {
        return x*5+Math.sin(x);
      }
    };

    public static final Function f2 = new Function() {
      public double eval(double x) {
        return Math.pow(x*f1.eval(-x),x);
      }
    };

    public static double TrapezoidalIntegration(double a,double b,int n,Function f)
    {
        // … using f.eval(x) to compute values

这篇关于模拟函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆