【发布时间】:2017-03-20 23:33:09
【问题描述】:
我对 c++ 完全陌生,并且认为编写一个解决给定升难题的程序是一个好习惯(你有 2 个容量为 3 升和 5 升的容器,你能得到 4 升吗?等等)
我为给定的容器编写了一个类和一个旨在将一个容器的内容“倒入”另一个容器的函数。尽管整个类是公共的,但该函数不会更改任何对象的内容的值。我不确定我做错了什么。
这是我的代码:
#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;
}
我确定我的错误很明显,但我无法在任何地方找到答案。任何帮助将不胜感激。
【问题讨论】:
-
通过引用而不是按值获取参数。
void pour(Container& a, Container& b)