你能帮忙用更详细的方式重写这个类吗 即(没有构造函数初始化列表和浮点运算符重载) 或解释它是如何工作的
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/