创建自定义运算符c ++ [英] Create custom operator c++

查看:420
本文介绍了创建自定义运算符c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问的是可能在C ++中定义自定义运算符ex。:

I'd like to ask is possible define custom operator in C++ ex.:

Func function;
double a[2] = {-3, 3};
function = function integrate a;

注意:integration是在<-3,3>之间进行数字积分的运算符。

Note: integrate is operator for numeric integration over interval <-3, 3>.

我真的很感兴趣,我只能创建自己的操作符。

I'm really interested only how I can create my own operator.

感谢您的回复和时间。
Mari

Thank you for yours responses and time. Mari

推荐答案

为什么你不是为你的集成方法写一个类(也许是一个完整的类hierachy)或者功能也是足够的。然后为其指定要作为参数进行集成的函数(使用 std :: function )将允许这是一个函数指针,函子或lambda表达式)和集成的范围。这是我最近这样做的方式。例如在1D中:

Why don't you just write a class for your integration method (maybe a complete class hierachy) or a function is also sufficient. Then give it the function you want to integrate as a parameter (using std::function will allow this to be a function pointer, functor or lambda expression) and the range of your integration. This is the way I did this recently. For example in 1D:

#include <functional>
#include <iostream>

double integrate(std::function<double(double)> f, double a, double b)
{
    return (b-a)/2.0*(f(a)+f(b));
}

int main()
{
    std::cout << integrate([](double x){ return x*x;}, -3.0, 3.0) << std::endl;
    return 0;
}

这篇关于创建自定义运算符c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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