Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to evaluate a function directly?

Tags:

c++

class

Title may not make any sense but I dont really know how to explain this. I have a class called polynomial and lets say I defined a polynome called p1 which is 2x+4. What I want to do is calculate p1(5) directly. I dont want anything like double calculate (polynomial) etc I want to be able to calculate my polynom with p1(x).

I hope my question is clear

like image 780
user2648701 Avatar asked Dec 29 '25 17:12

user2648701


1 Answers

Overload the function-call operator:

struct polynomial
{
    double a, b;
    polynomial(double m, double n) : a(m), b(n) { }  // represents "a * x + b"

    double operator()(double x) const
    {
        return a * x + b;
    }
};

Usage:

polynomial p(2.5, 3.8);

double val = p(1.0);
like image 183
Kerrek SB Avatar answered Jan 01 '26 09:01

Kerrek SB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!