重载函数类中的调用操作符 [英] Overload Function Call Operator in a Class

查看:96
本文介绍了重载函数类中的调用操作符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的教授给我的.h文件中,他写了

In the .h file given to me by my professor, he's written

    double operator()(double x) const;

重载的点是读取x作为double,并使用它来计算多项式存储在类对象Term中。我在类实现中提出的是

The point of the overload is to read in x as a double and use it to evaluate a polynomial that's stored in the class object Term. What I've come up with in the class implementation is

    double operator()(double x) const
    {   double result = 0.0;
        for (int i = 0; i < getSize(); i++)
            result += (getCoeff(i) * pow(x, getExponent(i)));
        return result;
    }

如何从应用程序调用它?我尝试了不同的调用,如

How do I call it from the application? I've tried different calls like

    Polynomial p;
    p.operator(x);

    Polynomial::operator(x);

    operator(x);

但总是在编译时出错。

推荐答案

通常的形式是调用它如同你的实例是一个函数:

The usual form is to call it as if your instance was a function:

double x = 3.1416;
Polynomial p;
double y = p(x);

或者,您可以显式调用运算符:

Alternatively, you can explicitly call the operator:

double x = 3.1416;
Polynomial p;
double y = p.operator()(x);

以下是一个简化示例:

#include <iostream>

struct Foo
{
  double operator()(double x) const { return x*2; }
};

int main()
{
  Foo f;
  std::cout << f(2.5) << std::endl;
}

这篇关于重载函数类中的调用操作符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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