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

前端 未结 12 1742
傲寒
傲寒 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 05:46

    So a big problem that I see with the lambda solutions provided is that z is calculated each time that it is inspected even if neither x nor y has changed. To get around this you really need to link these variables. I would suggest doing that via class:

    class foo {
        int x;
        int y;
        int z;
        void calculate() { z = (x + y) / 2; }
        friend istream& operator >>(istream& lhs, foo& rhs);
    public:
        void set_x(const int param) {
            x = param;
            calculate();
        }
        int get_x() const { return x; }
        void set_y(const int param) {
            y = param;
            calculate();
        }
        int get_y() const { return y; }
        int get_z() const { return z; }
    };
    
    istream& operator >>(istream& lhs, foo& rhs) {
        lhs >> rhs.x >> rhs.y;
        rhs.calculate();
        return lhs;
    }
    

    This will recalculate z each time x or y is set. This is a good solution if you access z frequently, and x and y are set infrequently. If x and y are set frequently or calculate is expensive you might consider:

    class foo {
        int x;
        int y;
        int z;
        bool dirty;
        void calculate() { z = (x + y) / 2; }
        friend istream& operator >>(istream& lhs, foo& rhs);
    public:
        void set_x(const int param) {
            x = param;
            dirty = true;
        }
        int get_x() const { return x; }
        void set_y(const int param) {
            y = param;
            dirty = true;
        }
        int get_y() const { return y; }
        int get_z() const { 
            if(dirty) {
                calculate();
            }
            return z;
        }
    };
    
    istream& operator >>(istream& lhs, foo& rhs) {
        lhs >> rhs.x >> rhs.y;
        rhs.dirty = true;
        return lhs;
    }
    

    Note that I've included an extraction operator, so whichever you choose your code can turn into something as simple as:

    foo xyz;
    
    cin >> xyz;
    cout << xyz.get_z();
    

提交回复
热议问题