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

标签 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;
};

最佳答案

我将解释这是如何工作的:

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()?

关于c++ - 解构c++类运算符重载和构造函数初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53443846/

相关文章:

c++ - 与 CPU 版本相比,OpenCV GPU 对象检测速度较慢且检测次数较少

c++ - 共享内存中的鲁棒互斥体并不那么鲁棒

php - "public"和 "public static"之间的区别?

c++ - 不了解如何为源/接收器类逻辑初始化指针

java - Java 中比较器接口(interface)的构造函数

c++ - Pthread 条件变量是连续轮询的替代品,是真的吗?

c++ - 如何从for循环中获取值的总和

java - A 类中的构造函数 A 不能应用于给定类型;

constructor - PowerMock + Mockito 模拟构造函数不起作用

Matlab类方法错误