引用类内部的类对象不起作用

时间:2019-07-10 12:36:17

标签: c++ class object

我正试图编写一个程序来解决“硬桶难题”,除了引用类对象的“倒入功能”以外,大多数代码都能正常工作。

我已经仔细检查了倾倒功能中的心律失常,并检查了该功能正在读取正确的容量

    #include "stdafx.h"
    #include <iostream>
    #include <string>

    using namespace std;

    class Bucket{
    private:
string name;
int capacity, contents;

    public:
Bucket(string name_, int capacity_){
    name = name_;
    capacity = capacity_;
}
void Print(){
    cout << "Bucket Name: " << name << endl;
    cout << "Capacity: " << capacity << " Gallons" << endl;
    cout << "Contents: " << contents << " Gallons" << endl;
}
void Fill(){
    contents = capacity;
}
void Empty(){
    contents = 0;
}
void Pour(Bucket A){
    if (contents + A.contents > A.capacity){
        contents -= A.capacity;
        A.contents = A.capacity; //Error Here
    }
    else{
        A.contents += contents; //Error Here
        contents = 0;
    }
}
    };

    int main(){
Bucket A1("A", 3), A2("B", 5);
int x;

cout << "0 - Exit" << endl << "1 - Fill Bucket A" << endl;
cout << "2 - Empty Bucket A" << endl << "3 - Pour A into B" << endl;
cout << "4 - Fill Bucket B" << endl << "5 - Empty Bucket B" << endl;
cout << "6 - Pour B into A" << endl << "7 - Print" << endl;
cout << "8 - Solve Die Hard Puzzle" << endl;

cin >> x;

while (x != 0){
    switch (x){
    case 0:{
               return 0;
    }
    case 1:{
               A1.Fill();
               A1.Print();
               cin >> x;
               break;
    }
    case 2:{
               A1.Empty();
               A1.Print();
               cin >> x;
               break;
    }
    case 3:{
               A1.Pour(A2);
               A1.Print();
               A2.Print();
               cin >> x;
               break;
    }
    case 4:{
               A2.Fill();
               A2.Print();
               cin >> x;
               break;
    }
    case 5:{
               A2.Empty();
               A2.Print();
               cin >> x;
               break;
    }
    case 6:{
               A2.Pour(A2);
               A1.Print();
               A2.Print();
               cin >> x;
               break;
    }
    case 7:{
               A1.Print();
               A2.Print();
    }
    case 8:{
               A2.Fill();
               A2.Pour(A1);
               A2.Fill();
               A2.Pour(A1);
               A2.Print();
    }
    default:{
                cout << "Invailid Input." << endl;
                cin >> x;
                break;
    }
    }
}
return 0;
    } 

程序会为倒入的铲斗输出不正确的内容,输出0而不是实际数字

0 个答案:

没有答案