Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
907 views
in Technique[技术] by (71.8m points)

oop - function doesn't change object attributes in c++

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...