我为给定的容器编写了一个类,并编写了一个旨在将一个容器的内容倒"入另一个容器的函数.尽管整个类都是公共的,但是该函数不会更改任何对象的内容的值.我不确定自己在做什么错.这是我的代码:#include <iostream>using namespace std;class Container { public: int quantity; //quantity of water in container int size; //max amt of water};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; }};int main() { Container bottle1; bottle1.quantity = 5; bottle1.size = 6; Container bottle2; bottle2.quantity = 0; bottle2.size = 2; pour(bottle2, bottle1); cout << bottle1.quantity << ", " << bottle2.quantity << endl; return 0;}我确定我的错误很明显,但是我找不到任何答案.任何帮助将不胜感激.解决方案您正在将Container作为副本传递.这意味着您在pour函数中更改的容器会在函数退出时被破坏.解决方案是使用引用:void pour(Container& a, Container& b)类型后的&表示引用.这意味着该函数可以访问与调用方相同的a和b,而不是在pour内部使用a和b的副本.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, can you obtain 4 liters? etc.) I wrote a class for a given container and a function which was intended to 'pour' the contents of one container into another. The function doesn't change the value of the contents of any object however, despite the entire class being public. I'm not sure what I'm doing wrong.Here is my code:#include <iostream>using namespace std;class Container { public: int quantity; //quantity of water in container int size; //max amt of water};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; }};int main() { Container bottle1; bottle1.quantity = 5; bottle1.size = 6; Container bottle2; bottle2.quantity = 0; bottle2.size = 2; pour(bottle2, bottle1); cout << bottle1.quantity << ", " << bottle2.quantity << endl; return 0;}I'm sure my mistake is obvious but I can't find an answer anywhere. Any help would be greatly appreciated. 解决方案 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. 这篇关于函数不会更改c ++中的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-29 13:33