试图修改类中的变量

时间:2018-01-22 21:30:26

标签: c++ class

嘿所以我试图修改变量计数器但是在我尝试设置它之后它仍然保持输出为零。我究竟做错了什么?如何修改变量计数器,以便通过增加函数更新它。该程序应该能够在用户指定位置开始时向上和向下计数

#include <iostream>
#include <stdlib.h>

using namespace std;

class CounterType
{
public:

    void increase();
    void decrease();
    void display();
    void setting(int newNumber);
    void CurrentDisplay();
    int counter;

};

int main()
{
    CounterType counter;
    int x;
    int whichCase;
    cout << "Please enter a number to start counting at" << endl;
    cin >> x;
    counter.setting(x);
    int Continue = 1;
    counter.CurrentDisplay();
    while (Continue == 1)
    {

        cout << "Push 1: Increase" << endl;
        cout << "Push 2: Decrease" << endl;
        cout << "Push 3: Display" << endl;
        cin >> whichCase;
        while (whichCase > 3 || cin.fail() || whichCase < 1)
        {
            cout << "No such case exists you dummy" << endl;
            cout << "Please enter a valid number" << endl;
            cin >> whichCase;
        }
        switch (whichCase)
        {
            case 1:
                counter.increase();
            case 2:
                counter.decrease();
            case 3:
                counter.display();
        }
        cout << "Would you like to continue? 1 for yes 2 for no" << endl;
        cin >> Continue;
        while (Continue > 2 || Continue < 1 || cin.fail())
        {
            cout << "Please enter a valid number: " << endl;
            cin >> Continue;
        }
    }
    return 0;
}

void CounterType::setting(int newNumber)
{

    if (newNumber >= 0)
        counter = newNumber;
    if (newNumber < 0)
    {
        cout << "Please enter a valid number. Program exited" << endl;
        exit(1);
    }
}

void CounterType::increase()
{
    counter = counter + 1;
}
void CounterType::decrease()
{
    if (counter = 0)
    {
        cout << "Cannot decrease any further" << endl;
        counter = 0;
    }
    if (counter > 0)
    {
        counter = counter - 1;
    }
}
void CounterType::display()
{
    cout << "Counter is " << counter << endl;
    ;
}
void CounterType::CurrentDisplay()
{
    cout << "Counter is " << counter << endl;
}

1 个答案:

答案 0 :(得分:1)

这一行:

if (counter = 0)

counter设置为0,然后将其测试为非零值。 你想做的可能是:

if (counter == 0)

此外,您的switch语句缺少break语句。取代

switch(whichCase)
{
case 1:
    counter.increase();
case 2:
    counter.decrease();
case 3:
    counter.display();
}

switch (whichCase)
{
    case 1:
        counter.increase();
        break;
    case 2:
        counter.decrease();
        break;
    case 3:
        counter.display();
}

并且,您应该初始化计数器,例如像这样:

CounterType counter{ 0 };

或者更好的是,为CounterType创建一个构造函数并在那里初始化counter成员变量。