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

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

    This sounds like the XY problem (pun intended).

    From the sound of it, you are not really writing code according to good object oriented practices. I would advise you not to use the "tricks" other people have suggested, but to actually learn how to make better use of OO structure.

    Before I go into that, note that assignment is distinct from an equality relation. The = in C++ is assignment, which is not the same as the = in maths. There are some (but not many) programming languages that do support equality relations, but C++ is not one of them. The thing is, adding support for equality relations introduces a heap of new challenges, so it's not as simple as "why isn't it in C++ yet".

    Anyway, in this case, you should probably be encapsulating your related variables in a class. Then you can use methods to obtain the "up-to-date" information. For example:

    class Player {
        std::vector inventory;
        int cash;
    public:
        int inventory_total();
        int net_worth();
    }
    
    //adds up total value of inventory
    int Player::inventory_total() {
        int total = 0;
        for(std::vector::iterator it = inventory.begin(); it != inventory.end(); ++it) {
            total += *it;
        }
        return total;
    }
    
    //calculates net worth
    int Player::net_worth() {
        //we are using inventory_total() as if it were a variable that automatically
        //holds the sum of the inventory values
        return inventory_total() + cash;
    }
    
    
    ...
    
    
    //we are using net_worth() as if it were a variable that automatically
    //holds the sum of the cash and total holdings
    std::cout << player1.net_worth();
    

    I admit that adding this behaviour to a class is quite a bit more complicated than saying z = x + y, but it really is only a few extra lines of code.

    That would be very annoying and error prone if you forgot to call the function somewhere.

    In this case the object doesn't have a net_worth member variable, so you can't accidentally use it instead of calling the function.

提交回复
热议问题