How can I make a variable always equal to the result of some calculations?

前端 未结 12 1759
傲寒
傲寒 2021-02-02 05:34

In math, if z = x + y / 2, then z will always change whenever we replace the value of x and y. Can we do that in programming

12条回答
  •  温柔的废话
    2021-02-02 06:09

    You could write a class that encapsulates its state to update either when mutated or return the right result when requested :

    #include 
    
    template
    class DynamicCalc
    {
    public:
        DynamicCalc(const T& func, const U& memberOne, const V& memberTwo) :
            _func(func)
          , _memberOne(memberOne)
          , _memberTwo(memberTwo)
        {
    
        }
    
        void SetMemberOne(const U& memberOne) { _memberOne = memberOne; }
        void SetMemberTwo(const U& memberTwo) { _memberTwo = memberTwo; }
        auto Retrieve() { return _func(_memberOne, _memberTwo); }
    
        U GetMemberOne() { return _memberOne; }
        V GetMemberTwo() { return _memberTwo; }
    
    private: 
        T _func;
    
        U _memberOne;
        V _memberTwo;
    };
    
    int main() {
    
        auto func = [](int x, int y) {
            return x + y;
        };
        DynamicCalc c(func, 3, 5);
    
        c.SetMemberOne(5);
        std::cout << c.Retrieve();
    }
    

    In truth, if you're happy for the calculation to happen when the value is reuqested then the getters/setters are unnecessary.

提交回复
热议问题