解构c ++类运算符重载和构造函数初始化列表

时间:2018-11-23 09:26:43

标签: c++ oop constructor operators

您能以更详细的方式帮助重写此类吗? 即(没有构造函数初始化列表和浮点运算符重载) 或说明其运作方式

class HigPassFilter
{
public:
    HigPassFilter(float reduced_frequency)
        : alpha(1 - exp(-2 * PI*reduced_frequency)), y(0) {}

    float operator()(float x) {
        y += alpha * (x - y);
        return x - y;
    }
    int myfunc(bool x) { return 1; }

private:
    float alpha, y;
};

1 个答案:

答案 0 :(得分:2)

我将解释其工作原理:

class HigPassFilter
{
public:
    // Constructor of the class, with one parameter.
    HigPassFilter(float reduced_frequency)
    // initializer list initializes both data members of the class,
    // 'alpha' will be set to the result of '1 - exp(-2 * PI*reduced_frequency)'
    // and 'y' will be set to 0
        : alpha(1 - exp(-2 * PI*reduced_frequency)), y(0)
   // the body of the constructor is empty (good practice)
   {}

   // An overload of operator(), which performs a mathematical operation.
   // It will increment 'y' by 'alpha * (x - y)' and
   // return the difference of 'x' and 'y'
   float operator()(float x) {
        y += alpha * (x - y);
        return x - y;
    }

    // a simple function that returns always 1 and
    // will not used its parameter, causing an unused warning (bad practice)
    int myfunc(bool x) { return 1; }

private:
    // private data members
    float alpha, y;
};

What is this weird colon-member (“ : ”) syntax in the constructor?中了解更多信息。初始化列表是C ++的一个非常重要的功能,因此我建议您花一些时间来学习它们。在大多数情况下,您将在初始化器列表中初始化数据成员,这就是为什么仍然存在此功能的原因。

进一步阅读:Why override operator()?