【问题标题】:Deconstruct c++ Class operator overload and constructor initialization list解构 c++ 类运算符重载和构造函数初始化列表
【发布时间】:2018-11-23 09:26:42
【问题描述】:

你能帮助重写这个类吗? 即(没有构造函数初始化列表和浮点运算符重载) 或解释它是如何工作的

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

【问题讨论】:

标签: c++ oop constructor operators


【解决方案1】:

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

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

【讨论】:

  • 谢谢,现在了解构造函数语法,并且操作符将输入参数显式转换为浮点数,并使用 (float) 签名覆盖类构造函数,其中 y += alpha * (x - y);返回 x - y; ?
  • @davidgangy 欢迎您。如果这个答案有帮助,不要忘记接受它。根据您的评论,参数转换就像您使用的任何常用函数一样发生。它将重载 operator(),not 构造函数!阅读overload vs override
猜你喜欢
  • 1970-01-01
  • 2016-07-21
  • 1970-01-01
  • 1970-01-01
  • 2011-11-03
  • 2011-12-24
  • 2011-01-06
  • 2018-06-20
  • 1970-01-01
相关资源
最近更新 更多