小编Phi*_*del的帖子

函数不会改变c ++中的对象属性

我对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 …
Run Code Online (Sandbox Code Playgroud)

c++ oop

3
推荐指数
2
解决办法
1740
查看次数

标签 统计

c++ ×1

oop ×1