简体   繁体   English

函数类中的重载乘法(加法,…)运算符

[英]Overloading multiplication (addition, …) operator in function class

Sorry but I've got a complete noob-question. 抱歉,我有一个完整的菜鸟问题。 Have been trying to figure it out myself but I just can't seem to find the relevant information on google. 一直想自己弄清楚,但我似乎无法在Google上找到相关信息。

Let's put it like that, I have this piece of code: 让我们这样说,我有这段代码:

class function
{
public:
    double (*f)(double x);
    function(double f(double x)): f(f){}
    double evalf(double x){
        return this->f(x);
    };
    function operator*(const function& other) const {
        return function(this->f*other.f);
    };
};

the problem is that the *-overload does not work and the issue is that he can't figure out how to multiply the two f's. 问题是*超载不起作用,问题在于他不知道如何将两个f相乘。 Okay so here is what I did: I am calling the constructor using lambda expressions, for example 好的,这就是我的工作:例如,我使用lambda表达式调用构造函数

auto linear = [](double x){return x;};

and

auto blub = function(linear);

I figured out myself that 我发现自己

return function(this->f*other.f);

prolly won't work so what I tried was 完全无法正常工作,所以我尝试了

auto mul = [&](double x){return this->f(x) * other.f(x);};
return function(mul);

but this ain't work either. 但这也不起作用。 Funny thing is it seems to work outside of the function-class. 有趣的是,它似乎在函数类之外工作。

auto mul = [](double x){return linear*linear;};

works just fine. 效果很好。

Does anyone have a solution for me ? 有人对我有解决方案吗? Thanks in advance. 提前致谢。

As you discovered yourself, to multiply you need to use a lambda, but a lambda with a caputure can't be converted to a function pointer. 如您所知,要进行乘法运算,您需要使用lambda,但是具有捕获功能的lambda不能转换为函数指针。 So for what you did here 所以你在这里做什么

 auto mul = [&](double x){return this->f(x) * other.f(x);}; return function(mul); 

to work, you need to change f to 要工作,您需要将f更改为

std::function<double(double)> f

Together you end up with 你在一起最终

class function
{
public:
    std::function<double(double)> f;

    function(std::function<double(double)> f): f(f){}
    double evalf(double x){
        return f(x);
    };
    function operator*(const function& other) const {
        return function( [=]( double x ){ return this->f(x) * other.f(x); } );
    };
};

which then works, see Live on coliru 然后可以使用,请参阅在coliru上直播

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

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