Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
0 / 0 / 0
Регистрация: 01.12.2019
Сообщений: 2

В чем ошибка

28.04.2020, 12:43. Показов 306. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Функция outputFood (строка 233) должна выводить дату exp. date, заданную пользователем, а выводится дату из конструктора по умолчанию. Есть идеи, в чем проблема?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <iomanip>
#include <string>
#include <Windows.h>
using namespace std;
class Date
{
private:
    int day;
    int month;
    int year;
public:
    Date()
    {
        day = 0;
        month = 0;
        year = 0;
    }
    Date(int dayInit, int monthInit, int yearInit)
    {
        day = dayInit;
        month = monthInit;
        year = yearInit;
    }
    void setDay(int _day)
    {
        day = _day;
    }
    void setMonth(int _month)
    {
        month = _month;
    }
    void setYear(int _year)
    {
        day = _year;
    }
    void inpDate()
    {
        cout << "Input day: ";
        cin >> day;
        cout << "\nInput month: ";
        cin >> month;
        cout << "\nInput year: ";
        cin >> year;
    }
    int getDay()
    {
        return day;
    }
    int getMonth()
    {
        return month;
    }
    int getYear()
    {
        return year;
    }
    void printDate()
    {
        cout << year << "." << month << "." << day << endl;
    }
 
    friend ostream& operator<<(ostream& os, const Date& _date)
    {
        return os << _date.day << "." << _date.month << "." << _date.year;
    }
 
    friend istream& operator >> (istream& is, Date& _date)
    {
        return is >> _date.day >> _date.month >> _date.year;
    }
    const Date& operator=(Date& _date)
    {
        this->day = _date.day;
        this->month = _date.month;
        this->year = _date.year;
        return *this;
    }
    const bool operator<(Date& _date)
    {
        int x1, x2;
        x1 = this->day + this->month + this->year;
        x2 = _date.day + _date.month + _date.year;
 
        if (x1>x2) return true;
        else return false;
    }
};
class Food
{
private:
    char* name;
    int type; // 1-bulka, 2-pirojok, 3-pirojnoe
    double weight;
    Date expirationDate;
public:
    int quantity;
    double cost;
    static int count;
 
    Food()
    {
        name = new char[30];
        strcpy(name, "<missing>");
        type = 0;
        weight = 0.00;
        expirationDate.setDay(1);
        expirationDate.setMonth(1);
        expirationDate.setYear(2000);
        quantity = 0;
        cost = 0;
        count++;
    }
    Food(const char* _name, int _type, double _weight, int _day, int _month, int _year, int _quantity, double _cost)
    {
        name = new char[30];
        strcpy(name, _name);
        type = _type;
        weight = _weight;
        expirationDate.setDay(_day);
        expirationDate.setMonth(_month);
        expirationDate.setYear(_year);
        quantity = _quantity;
        cost = _cost;
        count++;
    }
    Food(Food& copyFood)
    {
        name = copyFood.name;
        type = copyFood.type;
        weight = copyFood.weight;
        copyFood.expirationDate = expirationDate;
        quantity = copyFood.quantity;
        cost = copyFood.cost;
        count++;
    }
    ~Food()
    {
        count--;
        cout << "Destructor initialized for Food " << name << " left " << count << " more positions" << endl;
    }
    char* getName()
    {
        return name;
    }
    int getType()
    {
        return type;
    }
    double getWeight()
    {
        return weight;
    }
    int getDateDay()
    {
        return expirationDate.getDay();
    }
    int getDateMonth()
    {
        return expirationDate.getMonth();
    }
    int getDateYear()
    {
        return expirationDate.getYear();
    }
    void printFd()
    {
 
        cout << "Name: " << name << endl;
        cout << "Type: " << type << endl;
        cout << "Weight: " << weight << endl;
        cout << "Date: ";
        expirationDate.printDate();
        cout << "Quantity: " << quantity << endl;
        cout << "Cost: " << cost << endl;
        cout << "_____________________________" << endl;
 
    }
    void inpFd()
    {
        cout << "\nInput name: ";
        SetConsoleCP(1251);
        cin >> name;
        SetConsoleCP(866);
        expirationDate.inpDate();
        cout << "\nInput type: ";
        cin >> type;
        cout << "\nInput weight: ";
        cin >> weight;
        cout << "\nInput quantity: ";
        cin >> quantity;
        cout << "\nInput cost per item: ";
        cin >> cost;
    }
    const Food& operator=(Food & eda)
    {
        this->name = eda.name;
        this->type = eda.type;
        this->expirationDate = eda.expirationDate;
        this->weight = eda.weight;
        this->quantity = eda.quantity;
        this->cost = eda.cost;
        return *this;
    }
    friend ostream& operator<<(ostream& os, const Food& eda)
    {
        return os << endl << eda.name << ", " << "expiration date: " << eda.expirationDate << ", " << "weight: " << eda.weight << ", quantity" << eda.quantity << ", cost" << eda.cost << endl;
    }
    friend istream& operator >> (istream& is, Food& eda)
    {
        return is >> eda.name >> eda.expirationDate >> eda.weight >> eda.quantity >> eda.cost;
    }
 
};
class Database
{
private:
    Food* foodBase;
public:
    Database()
    {
        foodBase = new Food[0];
    }
    Database(Food*& _foodBase)
    {
        foodBase = _foodBase;
    }
    ~Database()
    {
        cout << "Destructor has deleted foodBase.\n";
    }
    void outputFood()
    {
        cout << "| Name" << setw(17) << "| Type  " << "|Weight" << setw(9) << "|  Exp. Date" << setw(6) << "|Qt.|" << "Cost|" << endl;
        cout << "______________________________________________________" << endl;
        for (int i = 0; i < Food::count; i++)
        {
            cout << "| " << setw(11) << foodBase[i].getName() << "  |" << setw(3) << foodBase[i].getType() << "    | " << foodBase[i].getWeight() << " | " << foodBase[i].getDateDay() << "."
                << foodBase[i].getDateMonth() << "." << foodBase[i].getDateYear() << " |" << foodBase[i].quantity << setw(2) << "|" << setw(3) << foodBase[i].cost << " |" << endl;
        }
        cout << "______________________________________________________" << endl;
    }
};
 
int Food::count = 0;
 
int main()
{
    setlocale(LC_ALL, "Russian");
    Date Date1, Date2(19, 11, 2000);
    Food Food1("Круассан", 3, 0.12, 29, 05, 2020, 100, 35), Food2("Кордонблю", 1, 0.27, 29, 05, 2019, 84, 60), Food3("Картошка", 2, 0.34, 19, 05, 2020, 37, 25);
    Food* _eda = new Food[3]{ Food1, Food2, Food3 };
    Food::count /= 2;
    Database eda(_eda);
    eda.outputFood();
    return 0;
}
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
28.04.2020, 12:43
Ответы с готовыми решениями:

Ошибка method range of object global failed в чем ошибка
Sub ПроверкаВвода() Dim A As Range Dim B As Range Dim i As...

Ошибка при передаче параметров в функцию. Объясните, ребят, пожалуйста, в чем ошибка
Есть функция, которую необходимо отобразить в виде линий уровня. Далее с помощью простого симплекс-метода нужно найти минимальное значение...

Ошибка "Stack around the variable 'text' was corrupted"
Выскакивает ошибка Stack around the voriable 'text' was corrupted. Подскажите пожалуйста в чём ошибка. #include &lt;iostream&gt; ...

1
7804 / 6568 / 2988
Регистрация: 14.04.2014
Сообщений: 28,705
28.04.2020, 14:59
count должно быть полем Database.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
28.04.2020, 14:59
Помогаю со студенческими работами здесь

Ошибка -is not a valid integer value (не является допустимым целым значением), не понимаю в чем ошибка
//--------------------------------------------------------------------------- #include &lt;vcl.h&gt; #pragma hdrstop #include...

В чем ошибка?По одной строке нормально в базу заходят,а две сразу вылетает ошибка?
INSERT INTO `jos_menu` (`id`, `menutype`, `name`, `alias`, `link`, `type`, `published`, `parent`, `componentid`, `sublevel`, `ordering`,...

Реализовать через тип данных структура. При сборке и отладки возникает ошибка. В чем ошибка?
С++ в таблице из 5 строк хранятся данные о товарах: наименование, цена, количество. Определить и вывести наименование товара, цена которого...

Ошибка 2 error LNK2019, не пойму в чем ошибка
Выдает такую ошибку: Ошибка 2 error LNK2019: ссылка на неразрешенный внешний символ &quot;int __cdecl game(void)&quot; (?game@@YAHXZ) в...

В чем ошибка? При запуске программы открывается консоль и сразу ошибка о завершении программы
К тому же выдает warning: deprecated conversion from string constant to 'char*' . #include &lt;iostream&gt; #include &lt;string.h&gt; #include...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка.
Programma_Boinc 23.12.2025
Thinkpad X220 Tablet — это лучший бюджетный ноутбук для учёбы, точка. Рецензия / Мнение/ Перевод https:/ / **********/ gallery/ thinkpad-x220-tablet-porn-gzoEAjs . . .
PhpStorm 2025.3: WSL Terminal всегда стартует в ~
and_y87 14.12.2025
PhpStorm 2025. 3: WSL Terminal всегда стартует в ~ (home), игнорируя директорию проекта Симптом: После обновления до PhpStorm 2025. 3 встроенный терминал WSL открывается в домашней директории. . .
Как объединить две одинаковые БД Access с разными данными
VikBal 11.12.2025
Помогите пожалуйста !! Как объединить 2 одинаковые БД Access с разными данными.
Новый ноутбук
volvo 07.12.2025
Всем привет. По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне: Ryzen 5 7533HS 64 Gb DDR5 1Tb NVMe 16" Full HD Display Win11 Pro
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов На странице: https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/ нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином. Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов. . . .
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2025, CyberForum.ru