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

前端 未结 12 1758
傲寒
傲寒 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:02

    You can define the following lambda z which always returns the current value of x+y because x and y are captured by reference:

    DEMO

    int main()
    {
        int x;
        int y;
    
        const auto z = [&x, &y](){ return x+y; };
    
        std::cin  >> x; // 1
        std::cin  >> y; // 2
        std::cout << z() << std::endl; // 3
    
        std::cin  >> x; // 3
        std::cin  >> y; // 4
        std::cout << z() << std::endl; // 7
    }
    

提交回复
热议问题