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

Создать класс "Электронное Устройство"

06.03.2021, 13:29. Показов 1687. Ответов 10
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
РЕКЛАМНАЯ ТЕХНИКА
Помогите создать програму с++. Создать класс Электронный Устройство (с полями интерфейс, мощность, вес). Определить конструкторы, деструкторы, и методы для изменения и чтения значений полей данного класса. Перегрузить операцию () для установки значений полей объекта, операцию присвоения =, потоковые операции ввода >> и вывода << объектов. Определить производный класс Устройства Отображения Иформации (диагональ, разрешение, файл с информацией). Определить конструкторы, деструктор, методы или операторные функции ввода-вывода. В рамках иерархии классов построить полиморфическое кластер на основе виртуального метода для считывания мощности. Разработать класс Реклама, содержащая массив объекта класса Устройство Отображения Информации. Вывести рекламу на устройства отображения информации. Для работы с массивом объектов построить и использовать класс итератор.
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#include <iostream>
#include <cstring>
#include <string>
#include <conio.h>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <algorithm>
#include <locale>
#include <ctime>
#include <Windows.h>
#include <string.h>
#include <stdlib.h>
#pragma warning (disable: 4996)
using namespace std;
class device
{
protected:
    int interfase;
    int power;
    int weight;
public:
    device(int interfase, int power, int weight)
    {
        this->interfase = interfase;
        this->power = power;
        this->weight = weight;
    }
    virtual void interffase(int x)
    {
        char s[10], st[20] = "Interfase ";
        itoa(x, s, 10);
        strcat(st, s);
        system(st);
    }
    device()
    {
        interfase = 0;
        power = 0;
        weight = 0;
    }
    device(device& d)
    {
        interfase = d.interfase;
        power = d.power;
        weight = d.weight;
    }
    ostream& operator<<(ostream& os)
    {
        os << interfase << power << weight;
        return os;
    }
    istream& operator>>(istream& is)
    {
        is >> interfase >> power >> weight;
        return is;
    }
    device& operator = (device& obj)
    {
        interfase = obj.interfase;
        power = obj.power;
        weight = obj.weight;
        return *this;
    }
    ~device();
 
private:
 
};
 
class Menu
{
protected:
    int count;
    int active;
    char** command;
public:
    Menu(int count, int active, char**command)
    {
        this->count = count;
        this->active = active;
        this->command = new char*[count];
        for (int i = 0; i < count; i++)
        {
            this->command[i] = new char[20];
            strcpy_s(this->command[i], 20, command[i]);
        }
    }
    Menu()
    {
        count = 0;
        active = 0;
        command = NULL;
    }
    Menu(Menu& m)
    {
        count = m.count;
        active = m.active;
        command = new char*[m.count];
        for (int i=0; i < count;i++)
        {
            command[i] = new char[20];
            strcpy_s(command[i], 20, m.command[i]);
        }
    }
    ~Menu()
    {
        for (int i = 0; i < count; i++)
        {
            delete[]command;
        }
    }
    friend istream& operator>>(istream& is, Menu& m)
    {
        for (int i = 0; i < m.count; i++)
        {
            is >> m.command[i];
        }
        return is;
    }
    friend ostream& operator<<(ostream& os, Menu& m)
    {
        for (int i = 0; i < m.count; i++)
        {
            os << m.command[i] << endl;
        }
        return os;
    }
};
 
class Info :public device, public Menu
{
protected:
    int diagonal;
    int rozdil;
    char *info;
public:
    Info(char* info, int diagonal, int rozdil, device d, Menu m) :device(d), Menu(m)
    {
        this->diagonal = diagonal;
        this->rozdil = rozdil;
        this->info = new char[100];
        strcpy_s(this->info, 100, info);
    }
    Info(const Info& i)
    {
        //device
        interfase = i.interfase;
        power = i.power;
        weight = i.weight;
        //Menu
        count = i.count;
        active = i.active;
        command = new char*[i.count];
        for (int i = 0; i < count; i++)
        {
            command[i] = new char[20];
            strcpy_s(command[i], 20, command[i]);
        }
        // Info
        diagonal = i.diagonal;
        rozdil = i.rozdil;
        info = i.info;
    }
    ~Info()
    {
        delete[] info;
    }
    Info() :device(), Menu()
    {
        diagonal = 0;
        rozdil = 0;
        info = NULL;
    }
    friend istream& operator>>(istream& is, Info&i)
    {
        is >> i.interfase >> i.power >> i.weight;
        for (int i = 0; i < i.count; i++)
        {
            is >> i.command[i];
        }
        is >> i.info;
        return is;
    }
    friend ostream& operator<<(ostream& os, Info& i)
    {
        os << i.info << ' ';
        os << i.diagonal;
        os << i.rozdil;
        return os;
    }
    void set()
    {
        cin.ignore();
    }
    char* getname()
    {
        return info;
    }
    int get_diagonal()
    {
        return diagonal;
    }
    int get_rozdil()
    {
        return rozdil;
    }
    Info set(ifstream& f)
    {
        char str[100] = "";
        char*ptr;
        f.getline(info, 50);
        ptr = strtok(str, "\t");
        if (ptr)
        {
            strcpy(info, ptr);
        }
        ptr = strtok(str, NULL);
        if (ptr)
        {
            interffase(atoi(ptr));
        }
        return Info();
    }
    void print(ofstream&f)
    {
        f << info << '\n';
        f << diagonal << '\n';
        f << rozdil << '\n';
    }
    void print()
    {
        Info();
    }
};
 
class Queue
{
protected:
    queue<Info> q;
public:
    void Print();
    void Load();
    void Save();
    void Add();
    void Edit();
    void Del();
    void Find();
};
 
void Queue::Print()
{
    int i = 0;
    cout << "# Пристрій \n";
    cout << "-------------------------------------------------------------------\n";
    int n = q.size();
    queue <Info> t = q;
    while (!t.empty())
    {
        cout << ++i;
        t.front().print();
        t.pop();
    }
}
 
void Queue::Save()
{
    ofstream f("text.txt", ios::out);
    f << q.size() << '\n';
    queue<Info> t = q;
    while (!t.empty())
    {
        t.front().print(f);
        t.pop();
    }
    f.close();
}
 
void Queue::Add()
{
    Info dd;
    dd.set();
    q.push(dd);
}
 
void Queue::Edit()
{
    int i = 0, n;
    Print();
    cout << "Введите номер редактируемоо элемента > ";
    cin >> n;
    if (n < 1 || n > q.size())
    {
        fprintf(stderr, "Элемент с номером %d не существует\n", n); return;
    }
    n--;
    queue<Info> f, f2;
    Info dd;
    while (i < n)
    {
        f.push(q.front());
        q.pop();
        i++;
        //f.back().print();
    }
 
    dd = q.front();
    q.pop();
    dd.set();
 
    while (!q.empty())
    {
        f2.push(q.front());
        q.pop();
    }
 
    while (!f.empty())
    {
        q.push(f.front());
        f.pop();
    }
    q.push(dd);
 
    while (!f2.empty())
    {
        q.push(f2.front());
        f2.pop();
    }
}
void Queue::Del()//vector <osoba> &os)
{
    int i = 0, n;
    Print();
    cout << "Введите номер удаляемоо элемента > ";
    cin >> n;
    if (n < 1 || n > q.size())
    {
        fprintf(stderr, "Элемент с номером %d не существует\n", n); return;
    }
    n--;
    queue<Info> f, f2;
    while (i < n)
    {
        f.push(q.front());
        q.pop();
        i++;
        //f.back().print();
    }
 
    q.pop();
 
    while (!q.empty())
    {
        f2.push(q.front());
        q.pop();
    }
 
    while (!f.empty())
    {
        q.push(f.front());
        f.pop();
    }
 
    while (!f2.empty())
    {
        q.push(f2.front());
        f2.pop();
    }
}
void Queue::Find()
{
    int i = 0;
    char str[50];
    Print();
    cout << "Введите Фамилию> ";
    cin >> str;
    queue<Info> f = q;
 
    while (!f.empty())
    {
        if (strstr(f.front().getname(), str))
        {
            f.front().print(); i++;
        }
        f.pop();
 
        if (i == 0) cout << "Нет записей удовлетворяющих условие!" << endl;
    }
}
int men(void) {
    int c = 0;
    struct tm* t;
    time_t ltime;
    time(&ltime);
    t = localtime(&ltime);
    cout << '\n' << t->tm_mday << '/' << t->tm_mon + 1 << '/' << 1990 + t->tm_year << endl;
 
    while ((c < '0' || c >9) && c != 21)
    {
        printf("\n>>>>>Menu<<<<<\n");
        printf("----------------\n");
        printf("[0] - Exit\n[1] - Add\n[2] - Save\n[3] - Load\n[4] - Print\n[5] - Find\n[6] - Del\n[7] - Edit\n");
        printf("----------------\n");
        printf("---->");
        c = getch();
        printf("%c\n", c);
    }
    return c;
}
 
 
void main()
{
    Queue os;
    int k;
    SetConsoleOutputCP(1251);
    char command[][6] = { "Add", "Save", "Load", "Print", "Find", "Del","Edit" };
    while ((k = men()) != 0 && k != 20)
        switch (k)
        {
        case'1': os.Add(); break;
        case'2': os.Save(); break;
        case'3': os.Load(); break;
        case'4': os.Print(); break;
        case'5': os.Find(); break;
        case'6': os.Del(); break;
        case'7': os.Edit(); break;
        }
 
    /*device f(1, 1, 80, 25, 2);
    cout << "Склад объекта ramka\n" << f;
 
    /*Menu m(7, 0, command);
    cout << "Склад объекта Menu\n" << m;
 
    Info w("MyInfo", f, m);
 
    cout << w << endl;*/
 
    system("pause");
}
Добавлено через 1 минуту
Помогите доделать
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
06.03.2021, 13:29
Ответы с готовыми решениями:

Создать класс Электронное Устройство
Помогите создать програму с++. Создать класс Электронный Устройство (с полями интерфейс, мощность, вес). Определить конструкторы,...

Создать класс Устройство сбора информации о погоде
Создать класс Устройство сбора информации о погоде состоящее из датчиков по заданию а. Для снятия значений создать класс генератор значений...

Создать класс "устройство ввода" и унаследовать от него три разных класса
Помогите создать иерархию типов: -Клавишное устройство ввода, имеющие количество клавиш(целое) и название клавиш(строки); -Роликовое...

10
0 / 0 / 0
Регистрация: 19.10.2021
Сообщений: 4
27.11.2021, 19:34
JumpingAdmiral, доделал?

Добавлено через 1 минуту
JumpingAdmiral, мне оно очень нужно
0
 Аватар для lemegeton
4903 / 2696 / 921
Регистрация: 29.11.2010
Сообщений: 5,783
28.11.2021, 18:10
Цитата Сообщение от Khrystynna Посмотреть сообщение
JumpingAdmiral, доделал?
Некропостинг.

Цитата Сообщение от JumpingAdmiral Посмотреть сообщение
Перегрузить операцию () для установки значений полей объекта
Цитата Сообщение от Khrystynna Посмотреть сообщение
мне оно очень нужно
Это условие непонятно. Как оно написано в оригинале?
Есть пример?
Что если поля разного типа?

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
#include <iostream>
 
class Device {
public:
    Device(): interface{0}, power{0}, weight{0} {}
    Device(int interface, int power, int weight): interface{interface}, power{power}, weight{weight} {}
 
    // остальные конструкторы и деструкторы -- тривиальные
    Device(const Device &) = default;
    virtual ~Device() = default;
 
    // оператор присваивания тоже в принципе тривиальный можно написать
    // Device &operator=(const Device &) = default;
    Device &operator=(const Device &other) {
        if (this != &other) {
            this->interface = other.interface;
            this->power = other.power;
            this->weight = other.weight;
        }
        return *this;
    }
 
 
    int getInterface() const {
        return interface;
    }
 
    void setInterface(int interface) {
        Device::interface = interface;
    }
 
    // построить полиморфическое кластер на основе виртуального метода для считывания мощности
    virtual int getPower() const {
        return power;
    }
 
    // построить полиморфическое кластер на основе виртуального метода для считывания мощности
    virtual void setPower(int power) {
        Device::power = power;
    }
 
    int getWeight() const {
        return weight;
    }
 
    void setWeight(int weight) {
        Device::weight = weight;
    }
 
private:
    int interface;
    int power;
    int weight;
};
 
 
std::ostream &operator<<(std::ostream &out, const Device &device) {
    return out << "Device{"
        "interface: " << device.getInterface() <<
               ", power: " << device.getPower() <<
               ", weight: " << device.getWeight() <<
               "}";
}
 
std::istream &operator>>(std::istream &in, Device &device) {
    int i, p, w;
    in >> i >> p >> w;
    device.setInterface(i);
    device.setPower(p);
    device.setWeight(w);
    return in;
}
 
class DisplayDevice : public Device {
public:
    DisplayDevice(): Device{}, diagonal{0}, resolution{0}, infofile{} {}
    DisplayDevice(int interface, int power, int weight, int diagonal, int resolution, const std::string &infofile)
        : Device{interface, power, weight}, diagonal{diagonal}, resolution{resolution}, infofile{infofile} {}
 
    // построить полиморфическое кластер на основе виртуального метода для считывания мощности
    int getPower() const override {
        return Device::getPower();
    }
 
    // построить полиморфическое кластер на основе виртуального метода для считывания мощности
    void setPower(int power) override {
        Device::setPower(power);
    }
 
    int getDiagonal() const {
        return diagonal;
    }
 
    void setDiagonal(int diagonal) {
        DisplayDevice::diagonal = diagonal;
    }
 
    int getResolution() const {
        return resolution;
    }
 
    void setResolution(int resolution) {
        DisplayDevice::resolution = resolution;
    }
 
    const std::string &getInfofile() const {
        return infofile;
    }
 
    void setInfofile(const std::string &infofile) {
        DisplayDevice::infofile = infofile;
    }
 
private:
    int diagonal;
    int resolution;
    std::string infofile;
};
 
std::ostream &operator<<(std::ostream &out, const DisplayDevice &device) {
    out << "DisplayDevice{"
        << static_cast<const Device &>(device)
        << ", diagonal: " << device.getDiagonal()
        << ", resolution: " << device.getResolution()
        << ", infofile: '" << device.getInfofile() << "'"
        << "}";
    return out;
}
 
std::istream &operator>>(std::istream &in, DisplayDevice &device) {
    in >> static_cast<Device&>(device);
    int d, r;
    std::string i;
    in >> d >> r >> i;
    device.setDiagonal(d);
    device.setResolution(r);
    device.setInfofile(i);
    return in;
}
 
DisplayDevice &operator<<(DisplayDevice &d, const std::string &advertisement) {
    std::cout << d << ": '" << advertisement << "'" << std::endl;
    return d;
}
 
class Advertisement {
public:
 
    // Для работы с массивом объектов построить и использовать класс итератор.
    using Iterator = DisplayDevice*;
    using ConstIterator = DisplayDevice const*;
 
    Advertisement(const std::initializer_list<DisplayDevice> &devices)
        : size{devices.size()}, devices{new DisplayDevice[size]} {
        std::copy(devices.begin(), devices.end(), Advertisement::devices);
    }
 
    // to keep things simple, let's pretend we shall not copy this object
    // or assign it one to another
    Advertisement(const Advertisement &other) = delete;
    Advertisement &operator=(const Advertisement &other) = delete;
 
    virtual ~Advertisement() {
        delete[] devices;
    }
 
    // Для работы с массивом объектов построить и использовать класс итератор.
    Iterator begin() {
        return devices;
    }
    Iterator end() {
        return devices + size;
    }
 
    ConstIterator begin() const {
        return devices;
    }
    ConstIterator end() const {
        return devices + size;
    }
 
    ConstIterator cbegin() const {
        return devices;
    }
    ConstIterator cend() const {
        return devices + size;
    }
 
    // Для работы с массивом объектов построить и использовать класс итератор.
    void advertise(const std::string &advertisement) {
        for (DisplayDevice &device : *this) {
            device << advertisement;
        }
    }
 
private:
    std::size_t size;
    DisplayDevice *devices;
};
 
int main() {
    Advertisement advertisement{
        DisplayDevice{1, 1000, 2000, 34, 3, "aaa"},
        DisplayDevice{2, 1000, 2000, 34, 3, "bbb"},
        DisplayDevice{3, 1000, 2000, 45, 4, "ccc"},
    };
 
    advertisement.advertise("buy our best product ever!");
 
    return 0;
}
0
0 / 0 / 0
Регистрация: 23.11.2021
Сообщений: 13
05.12.2021, 14:34
ну как там с кодами?
0
0 / 0 / 0
Регистрация: 06.03.2021
Сообщений: 5
05.12.2021, 17:18  [ТС]
Khrystynna, доделал
0
0 / 0 / 0
Регистрация: 23.11.2021
Сообщений: 13
05.12.2021, 20:14
lemegeton, а возможен ли способ с внешним итератором?

Добавлено через 23 минуты
JumpingAdmiral, ты реализовал задачу методом внутренней итерации?
0
0 / 0 / 0
Регистрация: 06.03.2021
Сообщений: 5
05.12.2021, 20:24  [ТС]
coolhazker, честно, я уже не помню, я это сдал и больше не вертался к плюсам

Добавлено через 29 секунд
coolhazker, могу скинуть код
0
0 / 0 / 0
Регистрация: 23.11.2021
Сообщений: 13
05.12.2021, 21:06
JumpingAdmiral, был бы не против

Добавлено через 19 минут
и был бы также очень признателен
0
 Аватар для lemegeton
4903 / 2696 / 921
Регистрация: 29.11.2010
Сообщений: 5,783
06.12.2021, 02:10
Цитата Сообщение от coolhazker Посмотреть сообщение
lemegeton, а возможен ли способ с внешним итератором?
В такой формулировке это высказывание имеет бесконечность смыслов.

Покажите задание целиком.
0
0 / 0 / 0
Регистрация: 23.11.2021
Сообщений: 13
06.12.2021, 10:47
lemegeton, Помогите создать програму с++. Создать класс Электронный Устройство (с полями интерфейс, мощность, вес). Определить конструкторы, деструкторы, и методы для изменения и чтения значений полей данного класса. Перегрузить операцию () для установки значений полей объекта, операцию присвоения =, потоковые операции ввода >> и вывода << объектов. Определить производный класс Устройства Отображения Иформации (диагональ, разрешение, файл с информацией). Определить конструкторы, деструктор, методы или операторные функции ввода-вывода. В рамках иерархии классов построить полиморфическое кластер на основе виртуального метода для считывания мощности. Разработать класс Реклама, содержащая массив объекта класса Устройство Отображения Информации. Вывести рекламу на устройства отображения информации. Для работы с массивом объектов построить и использовать класс итератор но он дожен быть внешним.
0
 Аватар для lemegeton
4903 / 2696 / 921
Регистрация: 29.11.2010
Сообщений: 5,783
06.12.2021, 14:14
Цитата Сообщение от JumpingAdmiral Посмотреть сообщение
Для работы с массивом объектов построить и использовать класс итератор.
Цитата Сообщение от coolhazker Посмотреть сообщение
Для работы с массивом объектов построить и использовать класс итератор но он дожен быть внешним.
То есть вы просто дописали руками к заданию от преподавателя "но он дожен быть внешним".
Эта формулировка по прежнему плохо раскрывает мысль, знаете ли.

Я так понял, вы хотите отдельный класс итератор вместо банального тайпдефа на указатели?
Не надо так делать, конечно, но вот:
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
#include <iostream>
 
class Device {
public:
    Device(): interface{0}, power{0}, weight{0} {}
    Device(int interface, int power, int weight): interface{interface}, power{power}, weight{weight} {}
 
    // остальные конструкторы и деструкторы -- тривиальные
    Device(const Device &) = default;
    virtual ~Device() = default;
 
    // оператор присваивания тоже в принципе тривиальный можно написать
    // Device &operator=(const Device &) = default;
    Device &operator=(const Device &other) {
        if (this != &other) {
            this->interface = other.interface;
            this->power = other.power;
            this->weight = other.weight;
        }
        return *this;
    }
 
 
    int getInterface() const {
        return interface;
    }
 
    void setInterface(int interface) {
        Device::interface = interface;
    }
 
    // построить полиморфическое кластер на основе виртуального метода для считывания мощности
    virtual int getPower() const {
        return power;
    }
 
    // построить полиморфическое кластер на основе виртуального метода для считывания мощности
    virtual void setPower(int power) {
        Device::power = power;
    }
 
    int getWeight() const {
        return weight;
    }
 
    void setWeight(int weight) {
        Device::weight = weight;
    }
 
private:
    int interface;
    int power;
    int weight;
};
 
 
std::ostream &operator<<(std::ostream &out, const Device &device) {
    return out << "Device{"
                  "interface: " << device.getInterface() <<
               ", power: " << device.getPower() <<
               ", weight: " << device.getWeight() <<
               "}";
}
 
std::istream &operator>>(std::istream &in, Device &device) {
    int i, p, w;
    in >> i >> p >> w;
    device.setInterface(i);
    device.setPower(p);
    device.setWeight(w);
    return in;
}
 
class DisplayDevice : public Device {
public:
    DisplayDevice(): Device{}, diagonal{0}, resolution{0}, infofile{} {}
    DisplayDevice(int interface, int power, int weight, int diagonal, int resolution, const std::string &infofile)
            : Device{interface, power, weight}, diagonal{diagonal}, resolution{resolution}, infofile{infofile} {}
 
    // построить полиморфическое кластер на основе виртуального метода для считывания мощности
    int getPower() const override {
        return Device::getPower();
    }
 
    // построить полиморфическое кластер на основе виртуального метода для считывания мощности
    void setPower(int power) override {
        Device::setPower(power);
    }
 
    int getDiagonal() const {
        return diagonal;
    }
 
    void setDiagonal(int diagonal) {
        DisplayDevice::diagonal = diagonal;
    }
 
    int getResolution() const {
        return resolution;
    }
 
    void setResolution(int resolution) {
        DisplayDevice::resolution = resolution;
    }
 
    const std::string &getInfofile() const {
        return infofile;
    }
 
    void setInfofile(const std::string &infofile) {
        DisplayDevice::infofile = infofile;
    }
 
private:
    int diagonal;
    int resolution;
    std::string infofile;
};
 
std::ostream &operator<<(std::ostream &out, const DisplayDevice &device) {
    out << "DisplayDevice{"
        << static_cast<const Device &>(device)
        << ", diagonal: " << device.getDiagonal()
        << ", resolution: " << device.getResolution()
        << ", infofile: '" << device.getInfofile() << "'"
        << "}";
    return out;
}
 
std::istream &operator>>(std::istream &in, DisplayDevice &device) {
    in >> static_cast<Device&>(device);
    int d, r;
    std::string i;
    in >> d >> r >> i;
    device.setDiagonal(d);
    device.setResolution(r);
    device.setInfofile(i);
    return in;
}
 
DisplayDevice &operator<<(DisplayDevice &d, const std::string &advertisement) {
    std::cout << d << ": '" << advertisement << "'" << std::endl;
    return d;
}
 
template<typename T, typename PointerType, typename ReferenceType>
struct PointerIterator {
 
    using value_type = T;
    using reference = ReferenceType;
    using pointer = PointerType;
    using difference_type = std::ptrdiff_t;
    using iterator_category = std::bidirectional_iterator_tag;
    using iterator = PointerIterator<T, PointerType, ReferenceType>;
 
    PointerIterator(pointer current): current{current} {}
    PointerIterator(): current{nullptr} {}
 
    reference operator*() { return *current; }
    reference operator*() const { return *current; }
    pointer operator->() { return current; }
    pointer operator->() const { return current; }
 
    iterator& operator++() { ++current; return *this; }
    iterator operator++(int) { return current++; }
 
    iterator& operator--() { --current; return *this; }
    iterator operator--(int) { return current--; }
 
    friend bool operator==(const iterator &a, const iterator &b) { return a.current == b.current; }
    friend bool operator!=(const iterator &a, const iterator &b) { return a.current != b.current; }
    friend bool operator<(const iterator &a, const iterator &b) { return a.current < b.current; }
    friend bool operator>(const iterator &a, const iterator &b) { return a.current > b.current; }
    friend bool operator<=(const iterator &a, const iterator &b) { return a.current <= b.current; }
    friend bool operator>=(const iterator &a, const iterator &b) { return a.current >= b.current; }
 
    iterator& operator+=(std::size_t size) { current += size; return *this; }
    friend iterator operator+(const iterator& i, std::size_t size) { return i.current + size; }
    friend iterator operator+(std::size_t size, const iterator&i) { return i.current + size; }
    iterator& operator-=(std::size_t size) { current -= size; return *this; }
    friend iterator operator-(const iterator&i, std::size_t size) { return i.current - size; }
    friend difference_type operator-(const iterator &a, const iterator &b) { return a.current - b.current; }
 
    reference operator[](std::size_t i) { return current[i]; }
 
    pointer current;
};
 
class Advertisement {
public:
 
    // Для работы с массивом объектов построить и использовать класс итератор.
    using Iterator = PointerIterator<DisplayDevice, DisplayDevice*, DisplayDevice&>;
    using ConstIterator = PointerIterator<DisplayDevice, const DisplayDevice*, const DisplayDevice&>;
 
    Advertisement(const std::initializer_list<DisplayDevice> &devices)
            : size{devices.size()}, devices{new DisplayDevice[size]} {
        std::copy(devices.begin(), devices.end(), Advertisement::devices);
    }
 
    // to keep things simple, let's pretend we shall not copy this object
    // or assign it one to another
    Advertisement(const Advertisement &other) = delete;
    Advertisement &operator=(const Advertisement &other) = delete;
 
    virtual ~Advertisement() {
        delete[] devices;
    }
 
    // Для работы с массивом объектов построить и использовать класс итератор.
    Iterator begin() {
        return devices;
    }
    Iterator end() {
        return devices + size;
    }
 
    ConstIterator begin() const {
        return devices;
    }
    ConstIterator end() const {
        return devices + size;
    }
 
    ConstIterator cbegin() const {
        return devices;
    }
    ConstIterator cend() const {
        return devices + size;
    }
 
    // Для работы с массивом объектов построить и использовать класс итератор.
    void advertise(const std::string &advertisement) {
        for (DisplayDevice &device : *this) {
            device << advertisement;
        }
    }
 
private:
    std::size_t size;
    DisplayDevice *devices;
};
 
int main() {
    Advertisement advertisement{
            DisplayDevice{1, 1000, 2000, 34, 3, "aaa"},
            DisplayDevice{2, 1000, 2000, 34, 3, "bbb"},
            DisplayDevice{3, 1000, 2000, 45, 4, "ccc"},
    };
 
    advertisement.advertise("buy our best product ever!");
 
    return 0;
}
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
06.12.2021, 14:14
Помогаю со студенческими работами здесь

Создать класс Man (человек), с полями: имя, возраст, пол и вес. Создать производный класс Student ...
Создать класс Man (человек), с полями: имя, возраст, пол и вес. Определить методы задания имени, возраста и веса. Создать производный класс...

Создать абстрактный базовый класс Тройка чисел с виртуальными методами увеличения на 1. Создать производный класс Время со своими функциями
Здравствуйте, пожалуйста помогите написать код к данной задаче, с таким условием: Создать абстрактный базовый класс Тройка чисел с...

Создать базовый класс Человек. Создать производный класс Сотрудник, содержащий следующие данные
Создать базовый класс Человек. Каждый объект класса должен содержать следующие данные: ФИО, год рождения, пол. Класс должен выполнять...

Описать класс «Устройство»
Описать класс «Устройство». Каждый объект содержит данные: производитель, модель, тип, расширение, поддерживаемые форматы (MJPEG, MPEG,...

Создать класс - данные - абстрактный базовый класс. Создать производные классы
Всем привет! У меня вот такая проблема.... Создать класс - данные - абстрактный базовый класс. Создать производные классы - данные типа...


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

Или воспользуйтесь поиском по форуму:
11
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru