function doesn't change object attributes in c++

前端 未结 2 1677
小蘑菇
小蘑菇 2020-12-19 11:53

I am totally new to c++ and thought it would be good practice to write a program which solved a given liter puzzle (you have 2 containers with capacities of 3 and 5 liters,

2条回答
  •  春和景丽
    2020-12-19 12:12

    This is probably because you're passing the objects by value. You'll want to pass them by reference. You can do this by changing your method header.

    Essentially, each instance of Container in the method header should become Container&. The call will not need to be changed.

    You can also pass pointers. Your arguments would then become Container *a, and in your call you'd have to add an ampersand (&) before each variable name (e.g. a becomes &a). You'd then also have to change any derefs of the object from periods (.) to arrows (->).

    Your method would become:

    void pour(Container *a, Container *b) {
    
        int differential = b->size - b->quantity;
    
        if (a->quantity <= differential) {
            b->quantity = a->quantity + b->quantity;
            a->quantity = 0;
        }
    
        else if (a->quantity > differential) {
            b->quantity = b->quantity - differential;
            a->quantity = a->quantity - differential;
        }
    
    };
    

    I mentioned both because in some cases, the designers of a program will adopt the convention that all references are const references. That is, any object passed by reference is not to be modified (which is enforced by using the const keyword before the type name in a method header), and that all other objects are passed by pointer. This makes it more clear, in the function call, whether or not an argument will be modified.

    The choice of using a const reference over pass-by-value in that convention is to improve the efficiency of a function call. It is quicker to pass a reference than to make a copy of an object.

提交回复
热议问题