function doesn't change object attributes in c++

前端 未结 2 1682
小蘑菇
小蘑菇 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-19 12:16

    You're passing the Containers as copies. This means that the containers you alter in the pour function are destructed upon function exit.

    The solution is to use references:

    void pour(Container& a, Container& b)
    

    The & after the type denotes a reference. This means that, instead of copies of a and b being used inside pour, the function gets access to the same a and b as the caller.

提交回复
热议问题