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

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

    Edit: While I fully answered the question as asked, please have a look at Artelius' answer, too. It addresses some issues my answer doesn't (encapsulation, avoidance of redundancies, risks of dangling references). A possible optimisation, if calculation is expensive, is shown in Jonathan Mee's answer.


    You mean something like this:

    class Z
    {
        int& x;
        int& y;
    public:
        Z(int& x, int& y) : x(x), y(y) { }
        operator int() { return x + y; }
    };
    

    The class delays calculation of the result until casted as int. As cast operator is not explicit, Z can be used whenever an int is required. As there's an overload of operator<< for int, you can use it with e. g. std::cout directly:

    int x, y;
    Z z(x, y);
    std::cin >> x >> y;
    if(std::cin) // otherwise, IO error! (e. g. bad user input)
        std::cout << z << std::endl;
    

    Be aware, though, that there's still a function call (the implicit one of the cast operator), even though it is not visible. And actually the operator does some true calculations (rather than just accessing an internal member), so it is questionable if hiding away the function call really is a good idea...

提交回复
热议问题