2017-10-16 122 views
-1

你有没有想法。返回初始状态只有一次

我想调用离散时间函数“执行”。 第一次调用:“execute”返回初始状态 每次下一次调用:“execute”返回一个计算值。

我用 “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; 
} 

我的问题: 是否有落实 “初始化” 到 “NormalExecution” -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_; 

}; 

Whished使用类

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 
} 

我的问题: 我喜欢以相同的方式处理每个算法。首先调用execute来提供Initstate。对于顶层的例子来说(取决于算法结构)。对于我的班级“IntegratorEB”没有。 (或只是问一个运行时间标志?!)

希望它会很清楚。

+0

什么是“NormalExecution”? – wally

+1

如果你知道第一个调用是什么,你就不清楚你的意思是“编译时间”,那么只需要使用两种方法:'init'和'execute',或者在构造函数中初始化并忘记init标志。闻起来像[xy问题](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。你为什么认为你需要这个?调用代码的外观如何? – user463035818

+0

“NormalExecution”:= else分支 – Oliver

回答

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