Как разрешить пользовательский ввод в объекты и классы? - PullRequest
0 голосов
/ 26 сентября 2018

Рассмотрим следующий код:

#include <iostream>
using namespace std;
class inventory
{
public:

    ~inventory()
    {
        cout << "This Object is being destroyed" << endl;
    }

    inventory()
    {
        itemNumber = 0;
        quantity= 0;
        cost= 0;
    }
    inventory(int itemNumber1, int quantity1, double cost1)
    {
        setItemNumber(itemNumber1);
        setQuantity(quantity1);
        setCost(cost1);


    }
    void setItemNumber(int itemNumber2)
    {
        itemNumber=itemNumber2;
    }
    bool setQuantity(int quantity2)
    {
        bool userTrue = true;
        bool userFalse = false;
        if (quantity2 < 0)
        {
            quantity = 0;
            return userFalse;
        }
        else
        {
            quantity= quantity2;
            return userTrue;
        }
    }
    bool setCost(double cost2)
    {
        bool userTrue = true;
        bool userFalse = false;
        if (cost2 < 0.0)
        {
            cost = 0.0;
            return userFalse;
        }
        else
        {
            cost= cost2;
            return userTrue;
        }
    }
    double getTotalCost(int quantity, double cost)
    {
        int total;
        total = (quantity * cost);
        return total;
    }
private:
    int itemNumber;
    int quantity;
    double cost;
};
int main()
{
    int itemNumberInput;
    int quantityInput;
    double costInput;
    cout << "Enter the Item Number: " << endl;
    cin >> itemNumberInput;
    cout << "Enter the Quantity : " << endl;
    cin >> quantityInput;
    cout << "Enter the Cost : " << endl;
    cin >> costInput;


    inventory *pointerA, *pointerB;
    pointerA = new inventory;
    pointerB = new inventory(inventory(itemNumberInput , quantityInput , costInput));
    inventory firstObject(itemNumberInput,quantityInput,costInput);




    int itemNumberInput1;
    int quantityInput1;
    double costInput1;
    cout << "Enter the Item Number: " << endl;
    cin >> itemNumberInput1;
    cout << "Enter the Quantity : " << endl;
    cin >> quantityInput1;
    cout << "Enter the Cost : " << endl;
    cin >> costInput1;
    inventory secondObject(itemNumberInput1,quantityInput1,costInput1); // not sure if thats correct
    cout << secondObject.setItemNumber(); // not working
    cout << secondObject.setQuantity(); // not working
    cout << secondObject.setCost(); // not working



    return 0;
}

Предполагается, что приведенный выше код будет принимать три пользовательских ввода и отправлять их классам, и классы будут выполнять свою работу.

IВ настоящее время я застрял в конце, где он дает мне ошибку.

Во втором объекте, где значения запрашиваются у пользователя, он должен отправить эти значения в классы.

Вместо этого,Я получаю сообщение об ошибке.

Как я могу решить эту проблему?

Ответы [ 2 ]

0 голосов
/ 28 сентября 2018

Вот фиксированный код: -

#include <iostream>
using namespace std;

class inventory
{
public:

    ~inventory()
    {
        cout << "This Object is being destroyed" << endl;
    }

    inventory()
    {
        itemNumber = 0;
        quantity= 0;
        cost= 0;
    }
    inventory(int itemNumber, int quantity, double cost)
    {
        this->itemNumber = itemNumber;
        this->quantity = quantity;
        this->cost = cost;


    }
    void setItemNumber(int itemNumber)
    {
        this->itemNumber=itemNumber;
    }

    bool setQuantity(int quantity)
    {
        bool userTrue = true;
        bool userFalse = false;
        if (quantity < 0)
        {
            this->quantity = 0;
            return userFalse;
        }
        else
        {
            this->quantity= quantity;
            return userTrue;
        }
    }

    bool setCost(double cost)
    {
        bool userTrue = true;
        bool userFalse = false;
        if (cost < 0.0)
        {
            this->cost = 0.0;
            return userFalse;
        }
        else
        {
            this->cost= cost;
            return userTrue;
        }
    }

    double getTotalCost(int quantity, double cost)
    {
        return quantity * cost;
    }

private:
    int itemNumber;
    int quantity;
    double cost;
};

int main()
{
    int itemNumberInput;
    int quantityInput;
    double costInput;
    cout << "Enter the Item Number: " << endl;
    cin >> itemNumberInput;
    cout << "Enter the Quantity : " << endl;
    cin >> quantityInput;
    cout << "Enter the Cost : " << endl;
    cin >> costInput;

    inventory *pointerA, *pointerB;
    pointerA = new inventory;
    pointerB = new inventory(inventory(itemNumberInput , quantityInput , costInput));
    inventory firstObject(itemNumberInput,quantityInput,costInput);

    int itemNumberInput1;
    int quantityInput1;
    double costInput1;
    cout << "Enter the Item Number: " << endl;
    cin >> itemNumberInput1;
    cout << "Enter the Quantity : " << endl;
    cin >> quantityInput1;
    cout << "Enter the Cost : " << endl;
    cin >> costInput1;
    // The below line is correct
    // inventory secondObject(itemNumberInput1,quantityInput1,costInput1); 

    //Alternatively
    inventory secondObject;
    secondObject.setItemNumber(itemNumberInput1); 
    secondObject.setQuantity(quantityInput1); 
    secondObject.setCost(costInput1); 

    delete pointerA; // delete dynamically allocated memory to avoid memory leak
    delete pointerB;

    return 0;
}
0 голосов
/ 26 сентября 2018

Итак, вы создали объект 'secondObject', используя конструктор из 3 аргументов, используя введенные пользователем значения в качестве параметров.Следовательно, переменные-члены этого объекта устанавливаются через конструктор, и использование методов 'set' не является действительно необходимым.В вашем случае, методы set будут полезны, если вы захотите изменить значения позже.Например, давайте представим, что пользователь вводит 10, 10 и 2.5 для значений.Затем вы используете конструктор для создания объекта с этими значениями.Разница лишь в том, что вы сначала помещаете эти значения в переменные.Но это работает так же.Если вы хотите изменить значение количества позже, вы можете сделать secondObject.setQuantity(2); И количество для этого объекта теперь установлено равным 2. Причина, по которой ваши вызовы .set не работают, заключается в том, что вам нужно передать параметрык этим методам, т.е. к значению, которое вы хотите установить.

Что касается печатаемого метода деструктора, объекты уничтожаются, когда они выходят из области видимости, и освобождается память.Обычно ничего не происходит с точки зрения вывода - объект просто выходит из области видимости, а компилятор освобождает память и занимается своим делом.Тем не менее, вы закодировали собственный деструктор, который выводит «Объект разрушается», который находится в конце основного.Скорее всего, ваш конструктор работает нормально, я просто не уверен, что вы ожидаете.Я бы также предложил вам ознакомиться с утечками памяти в C ++, особенно в отношении ключевого слова «new».

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...