仅返回初始状态

时间:2017-10-16 12:15:10

标签: c++ initialization

你可能有个主意。

我想调用离散时间函数"执行"。 第一个电话:"执行"返回一个init-state 每次下一个电话:"执行"返回计算值。

我的想法是" Initflag" (运行时):

while( true ){
  myValue = myObj.execute();
  doSomethingWith( myValue );
}

//Anywhere in a Class
public:
   float execute(){
     if( InitFlag ){
       InitFlag  = false; //now permanent set to false
       return 42;
     }
     else{
       return value = value + 42;
     }
}
private:
  bool InitFlag = true;
  float value = 0;
}

我的问题: 有没有办法实现" init"到"正常执行" -switchin到编译时间?没有永久地问旗帜?

存在更好的"关键字" /"描述"对于这个问题?

感谢您的帮助

//Bigger view

// One of my algorithm (dont take it, it´s not tested)

/// Integrator Euler-Backward 1/s Z-Transf. K*Ts*z/(z - 1) with K := slope, Ts := SampleTime
template<class T>
class IntegratorEB{//Euler Backward
public:
///CTOR
/// @brief Constructor
IntegratorEB(const T& K)
: Ts_(1.0), u_(0.0), y_(0.0), h_(K*Ts_), InitFlag_(true) {}
///END_CTOR

///ACCESS
    /// @brief copy and save input u
    void Input(const T& u){
        u_ = u;
    }

    //TODO First call should not change y_
    /// @brief calculate new output y 
    void Execute(){
        if( InitFlag ){
          y_ = y_; //or do nothing...
          InitFlag = false; 
        }
        else
          y_ = y_ + h_ * u_;  // y[k] = y[k-1] + h * u[k];
    }

    /// @brief read output, return copy
    T Output() const{
        return y_;
    }
    /// @brief read output, return reference
    const T& Output() const{
        return y_;
    }
///END_ACCESS
private:
    T Ts_;  //SampleTime
    T u_;   //Input u[k]
    T y_;   //Output y[k]
    T h_;   //Stepsize

    bool InitFlag_;

};

使用该类

1.Init 
2. Loop calls any algorithmen in the same way
2.1 Input
2.2 Execute
2.3 Output

使用其他算法进行调用的示例:

std::cout << "Class Statespace"; //Ausgabe  
for(int t = 1; t <= 50; ++t){
    DCMotor.Input(Matrix<float, 1, 1>(u));
    DCMotor.Execute();
    y = DCMotor.Output();
    std::cout << "t = " << t << " y = " << y; //Ausgabe
}

我的问题: 我喜欢以相同的方式处理每个算法。第一次执行调用提供Initstate。对于顶部的示例,它可以工作(取决于算法结构)。对于我的班级&#34; IntegratorEB&#34;不。 (或者只是询问运行时标志?!)

希望它会清楚。

1 个答案:

答案 0 :(得分:0)

// All instances share the same "value"
class foo {
public:
   float execute(){
       static float value = 0;
       return value = value + 42;
    }
 };


// Each instance has a separate "value"
class bar {
public:
   bar() : value(0) {}
   float execute(){
       return value = value + 42;
    }
private:
   float value;
 };
相关问题